I’m trying to make a function in SML that takes a list and an int and returns a list of all elements that are less than the int int * int list -> int list I wrote the following code:
- fun less (e, L) =
= map (fn a => if a < e then a else []) L;
also with the following code it doesnt work also:
- fun less (e, L) =
= map (fn a => if a < e then a) L;
and the error im getting is :
stdIn:22.15-22.38 Error: types of if branches do not agree [overload]
then branch: 'Z
else branch: 'Y list
in expression:
if a < e then a else nil
I think the problem is with the else part but I dont know what to put in it to work, anybody have any suggestion? I should use either map, foldl, or foldr functions.
EDIT:
- fun less (e, L) =
= let
= val acc = []
= in
= foldr (fn a => if a < e then a::acc else acc) acc L
= end;
still gives me error, the following error :
stdIn:241.3-241.54 Error: operator and operand don't agree [overload]
operator domain: 'Z * 'Y -> 'Y
operand: 'X -> 'X list
in expression:
foldr (fn a => if <exp> < <exp> then <exp> :: <exp> else acc)
The error message is clear; since
ahas typeintand[]has type'a list, their types are mismatched.The problem is you chose the wrong high-order function for the task. The
filteron List structure is best suited here:You could use recursion to implement
lessexplicitly, or usefoldl/foldrto accumulate filtered lists. However,mapseems irrelevant here.EDIT:
I will give a hint about using
foldl/foldr. You start with empty list as the accumulator. Prepend an element to the accumulator whenever that element is smaller thane; otherwise, return the accumulator.EDIT 2:
You forgot to pass
accas an argument in the lambda function:And the
let..in..endpart is redundant because you use[]as the accumulator only.