慢慢地获得列表匹配和尾递归的诀窍,我需要一个函数,它将列表“拼接”在一起,去掉中间值(显示起来容易,解释起来难):
合并[1;2;3;3;4;5;5;6;7] /-> 1;2;3;4;5;6;7
List.merge函数的代码如下所示:
///Like concat, but removes first value of each inner list except the first one
let merge lst =
let rec loop acc lst =
match lst with
| [] -> acc
| h::t ->
match acc with
| [] -> loop (acc @ h) t
| _ -> loop (acc @ (List.tl h)) t //first time omit first value
loop [] lst(好的,它不太像concat,因为它只处理两个级别的列表)
问:如何对Seq的Seq(不使用可变标志)执行此操作?
UPDATE (来自朱丽叶的评论):我的代码创建了由“段”组成的“路径”,这些“路径”基于选项类型:
type SegmentDef = Straight of float | Curve of float * float
let Project sampleinterval segdefs = //('clever' code here)当我做List.map时(项目1.)ListOfSegmentDefs,我得到一个列表,其中每个段开始于前一个段结束的同一点。我想把这些列表组合在一起,得到一条路径,只保留每个重叠的“顶部/尾部”--但我不需要做“集合”,因为我知道我没有任何其他副本。
发布于 2009-02-03 03:34:26
这基本上与您的第一个解决方案相同,但更简洁一些:
let flatten l =
seq {
yield Seq.hd (Seq.hd l) (* first item of first list *)
for a in l do yield! (Seq.skip 1 a) (* other items *)
}编辑添加
如果需要此代码的列表版本,请在方法末尾添加|> Seq.to_list:
let flatten l =
seq {
yield Seq.hd (Seq.hd l) (* first item of first list *)
for a in l do yield! (Seq.skip 1 a) (* other items *)
} |> Seq.to_list发布于 2010-07-08 23:22:01
let merge = function
| [] -> []
| xs::xss -> xs @ [for _::xs in xss do yield! xs]或者:
let merge = function
| [] -> []
| xs::xss -> xs @ List.collect List.tail xsshttps://stackoverflow.com/questions/502447
复制相似问题