Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you extract distinct elements from a list?

Tags:

f#

I'm pretty new to f# and I'm having a hard time trying to extract a list of distinct values from a list:

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

How do I do that? I see that seq has a distinct method, but not lists.

like image 516
Greg McGuffey Avatar asked Jun 04 '15 00:06

Greg McGuffey


2 Answers

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

Result:

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

Next F# version (4.0) will have List.distinct function

like image 182
Petr Avatar answered Nov 19 '22 17:11

Petr


Not sure if worse or better than Petr answer but you could also do :

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

> distinct [ 1; 2; 2; 3; 4; 3 ];;
val it : int list = [1; 2; 3; 4]
like image 34
Sehnsucht Avatar answered Nov 19 '22 17:11

Sehnsucht