I’ve come across 2 confusing problems in SML and was hoping someone could help me out:
The first is a function which takes an element and a list and decides whether that element exists in the list or not, here is the code I’ve attempted to write:
fun member (e,L) = foldl (fn(a,b) => if (e = b) then true else false) false L;
But I get bool * ‘a list –> bool but what I need is ”a * ”a list –> bool
As for the second, it also requires an element and a list but returns a list of elements less than the passed one. I’m not sure whether this should be done via map or foldr/foldl.
Any suggestions?
Thanks in advance 🙂
Regarding the first question, in
fn (a, b) => ...ais the next element andbis the accumulator. Since you compareewithb, e is infered to have typebool. You should compareewitha, and never overridebwhen it becomestrue:For the second question, you can use
foldr/foldlto do so. It’s similar to the first example; you start with empty list as the accumulator and prepend an element to it whenever that element is smaller than a threshold.As a tradeoff,
foldrgives you the right order but it isn’t tail-recursive. On the other hand,foldlis tail-recursive but gives resulting lists in a reverse order.