)I am just starting with SML and have been trying to write a function that takes two lists, L1 and L2, and returns a list of elements that occur in both. This is what I have so far:
fun exists x nil = false | exists x (h::t) = (x = h) orelse (exists x t);
fun listAnd L1 nil = nil
| listAnd nil L2 = nil
| listAnd L1 L2 = if exists(hd(L1) L2) = true then hd(L1)::(listAnd(tl(L1) L2)) else listAnd(tl(L1) L2);
I am not really sure where is the error.
Since
existsis a function taking two arguments, your mistake is to put extra parentheses around both arguments. For example,exists(hd(L1) L2)should corrected asexists (hd L1) L2.I have a few suggestions:
= true[]for empty list and wildcard_for unused valuesL1instead ofhdandtlNow this is the corrected function: