I'm trying to remove duplicates in a list with this function. It removes the duplicates, but returns the list in a reverse order. I'm a bit unsure how to fix that without an ugly solution.
There are already other answers that show various practical solutions to this, but I suppose you are interested in a minimal change to make your code work. When using accumulator in functional programming, you often end up reversing the list along the way - the standard solution to this is to reverse the list at the end, which you can do using List.rev:
let rd list=
let rec func list nlist=
match list with
| [] -> List.rev nlist // Reverse the list before returning it
| x::xs ->
if not (isMember x nlist) then
func xs (x::nlist)
else
func xs nlist
func list []
Aside from adding List.rev, I also changed the last line to func list [] (your code had add there, but this probably was a typo). I also changed isMember x nlist <> true to more idiomatic not (isMember x nlist).
You can do this to remove duplicates:
Seq.distinct [1;1;2;4;4;5;6]
It returns [1;2;4;5;6]
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