Reputation: 11
Need help with an SML problem I can't seem to solve. Basically I have two list and I need to return the greater from each list.
Example call:
Greater([8,4,12,5,6],[2,6,14,4,5]);
Would return (8,6,14,6).
I just started working with lists in SML and not even sure where to start on this.
Upvotes: 0
Views: 433
Reputation:
Assuming you have two lists of equal lengths you could define this function:
fun greater nil nil = nil
| greater (x::xs) (y::ys) =
if x > y then x::(greater xs ys) else y::(greater xs ys);
Or alternatively, by reducing the problem to a mapping from a list of int pairs to a list of ints:
fun zip nil nil = nil
| zip (x::xs) (y::ys) = (x,y)::(zip xs ys);
fun max (x,y) = if x > y then x else y;
fun greater xs ys = map max (zip xs ys);
Note that lists in ML are denoted as [1,2,3]
and not (1,2,3)
, which is a tuple with three elements. This function is then called as:
- greater [1,2,3,4] [2,3,4,5];
val it = [2,3,4,5] : int list
- greater [~1,8,3] [8,~1,~2];
val it = [8,8,3] : int list
Upvotes: 1
Reputation: 36118
val greater = List.map Int.max o ListPair.zip
Or to expand that out:
fun greater(nil, nil) = nil
| greater(x::xs, y::ys) = (if x > y then x else y)::greater(xs, ys)
| greater(_, _) = raise Domain
Upvotes: 3