I want to create a function that takes a list and returns a list with removed duplicates.
let removedupes list1 =
let list2 = []
let rec removeduprec list1 list2 =
match list1 with
| [] -> list2
| head :: tail when mem list2 head = false -> head :: removeduprec tail list2
| _ -> removeduprec list1.Tail list2
removeduprec list1 list2
Im using this "mem" function to go trough the list and see if the value already exists and in that case i want to continue with the recursion.
let rec mem list x =
match list with
| [] -> false
| head :: tail ->
if x = head then true else mem tail x
When i test this code i get
let list1 = [ 1; 2; 3; 4; 5; 2; 2; 2]
removedups list1;;
val it : int list = [1; 2; 3; 4; 5; 2; 2; 2]
Im thinking that the "head :: removeduprec tail list2", but im quite new to f# so not completely sure how this works.
I rewrote some of the logic to make things simpler. The problem was that you needed to add things to list2 as it was created, rather than afterwards - I moved the :: to inside the call like so
let rec mem list x =
match list with
| [] -> false
| head :: tail ->
if x = head then true else mem tail x
let removedupes list1 =
let rec removeduprec list1 list2 =
match list1 with
| [] -> list2
| head :: tail when mem list2 head = false -> removeduprec tail (head::list2)
| h::t -> removeduprec t list2
removeduprec list1 []
Just for completeness: in F# 4.0 the List module now has the distinct function doing exactly what OP wants.
List.distinct [1; 2; 2; 3; 3; 3];;
val it : int list = [1; 2; 3;]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With