Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove duplicates from a list in SML

I just started learning functional programming in SML and I want to know how I can combine the following two functions into a single function. The function isolate deletes the duplicates of a list of any type ('a) using the helper function 'removes'.

fun isolate [] = []
  | isolate (l as x::xs) = x::isolate(remove(x,xs))

fun remove (x,[]) = []
  | remove (x,l as y::ys) = if x = y then remove(x,ys) else y::remove(x,ys)

So, for the purpose of better understanding the constructs in the SML, how would you include the function remove within isolate? This may seem trivial, but I have thinking about it and can't figure it out. Thank you for your help!

like image 695
macalaca Avatar asked Jan 12 '14 16:01

macalaca


2 Answers

One method would be to just define remove inside isolate.

fun isolate [] = []
  | isolate (l as x::xs) =
      let fun remove (x,[]) = []
            | remove (x,l as y::ys) = if x = y
                                      then remove(x,ys)
                                      else y::remove(x,ys)
      in
        x::isolate(remove(x,xs))
      end

Alternately, to make deduplication one function, though all this really does is use the library function List.filter to do the same thing that remove does.

fun isolate [] = []
  | isolate (x::xs) = x::isolate(List.filter (fn y => y <> x) xs)
like image 75
qaphla Avatar answered Oct 21 '22 10:10

qaphla


My idea: define a nested function to check if there are duplicated elements in the list:

fun set(nums:int list)=
  let fun duplicate(x:int, l:int list)=
    if null l
    then false
    else hd l=x orelse duplicate(x,tl l)
  in
      if null nums
      then []
      else
      let val s=set(tl nums)
      in if duplicate(hd nums,s)
         then s
         else hd nums::s
      end
  end

But it will give a list that only remains the last one for every duplicated elements.

like image 1
Xinyi Li Avatar answered Oct 21 '22 09:10

Xinyi Li