Comparing lists in Standard ML

Posted by user1050640 on Stack Overflow See other posts from Stack Overflow or by user1050640
Published on 2011-11-16T22:44:38Z Indexed on 2011/11/17 1:51 UTC
Read the original article Hit count: 256

Filed under:
|

I am extremely new to SML and we just got out first programming assignment for class and I need a little insight.

The question is: write an ML function, called minus: int list * int list -> int list, that takes two non-decreasing integer lists and produces a non-decreasing integer list obtained by removing the elements from the first input list which are also found in the second input list.

For example,

minus( [1,1,1,2,2], [1,1,2,3] ) = [1,2]

minus( [1,1,2,3],[1,1,1,2,2] ) = [3]

Here is my attempt at answering the question. Can anyone tell me what I am doing incorrectly? I don't quite understand parsing lists.

fun minus(xs,nil) = []
| minus(nil,ys) = []
| minus(x::xs,y::ys) = if x=y then minus(xs,ys) else x :: minus(x,ys);

Here is a fix I just did, I think this is right now?

fun minus(L1,nil) = L1
| minus(nil,L2) = []
| minus(L1,L2) = if hd(L1) > hd(L2) then minus(L1,tl(L2))
    else if hd(L1) = hd(L2) then minus(tl(L1),tl(L2))
    else hd(L1) :: minus(tl(L1), L2);

© Stack Overflow or respective owner

Related posts about homework

Related posts about sml