Search code examples
recursionfunctional-programmingsmlsmlnj

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!


Solution

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