Search code examples
listsml

Deleting one list from another


I'm trying to write a program that deletes the list1 if it's in list2.

E.g

delete [1,2] [1,2,3,4]
  => [3,4]

I'm very close to solving it, but my code only removes the head of the first list from the second list, so...

delete [1,2] [1,2,3,4]
  => [2,3,4]

If anyone could help, that would be great :)

fun delete (hd1::tl1) [] = []
  | delete (hd1::tl1) (hd2::tl2) = 
      if hd1 = hd2 then delete (hd1::tl1) tl2 else hd2::delete(hd1::tl1) tl2;

Solution

  • You need to determine whether the entire first list is the start of the second list.

    And you want to build on what you did before - when you're studying, it is often the case that you've recently done something useful.

    Given a function start that determines whether one list is the start of another, you can write

    fun delete xs ys = if start xs ys
                       then <...>
                       else (hd ys) :: (delete xs (tl ys))
    

    The interesting part is left as an exercise (you have almost certainly seen library functions that can be used).