List F中列表的子列表#
如何获取子列表List F中列表的子列表#,list,f#,linked-list,List,F#,Linked List,如何获取子列表 [1]; [1; 2]; [1; 2; 3]; ...; [1; 2; 3; ...; n] 来自列表 [1; 2; 3; ...; n] 用最惯用的方式?我所能做的就是: List.scan (fun acc elem -> elem::acc) [] [1;2;3;4;5] > val it : int list list = [[]; [1]; [2; 1]; [3; 2; 1]; [4; 3; 2; 1]; [5; 4; 3; 2; 1]] 谢谢
[1]; [1; 2]; [1; 2; 3]; ...; [1; 2; 3; ...; n]
来自列表
[1; 2; 3; ...; n]
用最惯用的方式?我所能做的就是:
List.scan (fun acc elem -> elem::acc) [] [1;2;3;4;5]
> val it : int list list =
[[]; [1]; [2; 1]; [3; 2; 1]; [4; 3; 2; 1]; [5; 4; 3; 2; 1]]
谢谢。您的实现很好。以下是我的选择:
let source = [1..10]
let counts = [0..source.Length] // Or start at 1 if you don't want to start with an empty list
counts |> List.map (fun count -> source |> List.take count)
把我的扔到垃圾堆上,这也许是傻瓜回答的精妙之处:
let inits list =
list |> List.mapi (fun i _ -> List.take (i + 1) list)
mapi
是一个很有用的函数:您为它提供了一个函数,该函数将获取每个索引和项的值。下面是另一个函数:
let f n = List.init n (fun i -> [1..(i + 1)])
List.init用于初始化列表。不知道是否有惯用的方法,但您的方法很好(只需添加一个映射来反转列表)-顺便说一句:它被称为
heads
;)有更多的子列表;)我说的是List.scan(fun acc elem->elem::acc)[[1;2;3;4;5]|>List.map List.rev |>List.tail
doh my bad。。。它可能被称为inits而不是heads,OP的版本要好得多though@Carsten你为什么这么说?对我来说,这更简单。它在输入列表上迭代两次,但只创建每个输出子列表一次,因为不需要反转。它将调用take
n次。这只是一个品味问题-对我来说,OP的答案更接近于在性能相关的情况下(使用snoc列表)执行的方式-如果您可以忽略错误的顺序(并忽略/不使用List.map List.rev
)这只是更好的选项我在列表
模块中找不到take
方法,它只存在于F#4.0及更高版本中。您可以使用以下命令将其添加到列表模块:module List=let take n l=Seq.take n l |>Seq.toList
。我只将其放在一行,因为这是一条注释。