0

I've been asked to write a Standard ML Program which deletes every occurrence of a list from another list. For the life of me I cannot understand what is wrong with my code. Any help would be appreciated! My input for this program is as follows:

deleteAll [1,2,3] [3,2,1,2,3,2,1,2,3];

However my output is this:

val it = [3,2,2,1,2,3] : int list

When it should be: [3,2,2];

fun length(x) = if x = [] then 0 else 1+length(tl(x));

val length = fn : ''a list -> int

fun drop 0 L = L
|   drop n [] = raise c4
|   drop n (h::t) = drop (n-1) t;

val drop = fn : int -> 'a list -> 'a list

fun starts [] _ = true
|   starts _ [] = false
|   starts (h::t) (x::xs) = if(h=x) then starts t xs else false;

val starts = fn : ''a list -> ''a list -> bool


fun deleteAll [] _ = []
|   deleteAll xs [] = xs
|   deleteAll (x::xs) (y::ys) = if(starts (x::xs) (y::ys))
    then deleteAll (x::xs) (drop (length(x::xs)) (y::ys))
    else y::(deleteAll (x::xs) ys);
val deleteAll = fn : ''a list -> ''a list -> ''a list

1 Answers1

0

First you don't need to create a length function as length is a build-in function that returns an int representing the elements of an 'a list.

One more thing, you raise an exception c4 in your function drop. Then you should also include that in the beginning of your program.

The primary reason your code doesn't work is your deleteAll function base cases. The corrected version should be:

fun deleteAll [] xs = xs (* when the first list is empty, it should return the original list *)
|   deleteAll xs [] = [] (* when the second list is empty, it should return an empty list *)
|   deleteAll (x::xs) (y::ys) = if(starts (x::xs) (y::ys))
                                then deleteAll (x::xs) (drop (length(x::xs)) (y::ys))
                                else y::(deleteAll (x::xs) ys);

The rest is good! After the change the answer should be correct : )

- deleteAll [1,2,3] [3,2,1,2,3,2,1,2,3];
val it = [3,2,2] : int list
angerhang
  • 327
  • 4
  • 13