如何从列表中提取不同的元素?

How do you extract distinct elements from a list?

我是 f# 的新手,我很难尝试从列表中提取不同值的列表:

let myList = [ 1; 2; 2; 3; 4; 3 ]
// desired list
[ 1; 2; 3; 4 ]

我该怎么做?我看到 seq 有一个 distinct 方法,但没有列表。

let myList = [ 1; 2; 2; 3; 4; 3 ]
let distinctList = myList |> Seq.distinct |> List.ofSeq

结果:

> 
val myList : int list = [1; 2; 2; 3; 4; 3]
val distinctList : int list = [1; 2; 3; 4]

下一个 F# 版本 (4.0) 将具有 List.distinct 函数

不确定是否比 更差或更好,但您也可以这样做:

let distinct xs = xs |> Set.ofList |> Set.toList

> distinct [ 1; 2; 2; 3; 4; 3 ];;
val it : int list = [1; 2; 3; 4]