在一个列表中复制到新列表

时间:2012-11-27 12:05:22

标签: list f#

我有这个函数需要一个列表和检查重复项,如果发现任何重复项,它们会被添加到这样的新列表中:

let foo1 z list = list |> List.filter (fun e -> e <= z)

这给出了foo1 1 [2; 3; 4; 1; 5; 1; 6; 1] =&gt; [1; 1; 1] 问题是我不想使用f#

中的任何内置函数

1 个答案:

答案 0 :(得分:4)

你已经在列表处理上询问了一些基本的F#问题,所以我建议先阅读一些介绍并亲自尝试。

使用内置函数是在实践中解决问题的正确方法。如果你想学习F#并理解递归,那么请先阅读上面的内容。然后你应该能够写出类似的内容:

let rec duplicates z = function
  // If the list is empty, return empty list of duplicates
  | [] -> []
  // If it starts with 'z' then return one duplicate and recursively process the rest
  | x::xs when x = z -> x::(duplicates x xs)
  // If it starts with something else, then skip the first element and process the rest
  | x::xs -> duplicates z xs

有许多F#介绍解释了filter和类似函数的实现方式。您可以在大多数F#书籍中找到F# wikibook covers this topic(请参阅a list on fsharp.org)和www.tryfsharp.org上的Working lists部分。