Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# Remove Duplicates

Tags:

list

recursion

f#

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.

like image 538
alexanderson Avatar asked Sep 28 '26 19:09

alexanderson


2 Answers

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).

like image 56
Tomas Petricek Avatar answered Oct 01 '26 21:10

Tomas Petricek


You can do this to remove duplicates:

Seq.distinct [1;1;2;4;4;5;6]

It returns [1;2;4;5;6]

like image 25
Axel Prieto Avatar answered Oct 01 '26 21:10

Axel Prieto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!