Reputation: 13
I'm new to ML so I'm doing my best to understand.
Write an ML function called alternate : 'a list -> 'a list
, that takes two lists, having the same length, as input and produces an output list whose elements are alternately taken from the first and second input list respectively.
Example
alternate ([1,3,5],[2,4,6]) = [1,2,3,4,5,6]
This is my work : fun alternate ( x::xs,y::ys) = x::alternate(x,y);
Upvotes: 0
Views: 364
Reputation: 16105
You split the problem in two: A recursive case and a base case. (1) In the recursive case you solve some unit of the problem, in this case placing a single element from each list in front of the result, and recursively try to solve the rest of the problem in the same fashion. (2) In the base case, the lists are empty and the result is the empty list.
fun alternate (x::xs, y::ys) = x::y::alternate(xs, ys)
| alternate ([], []) = []
| alternate _ = raise Fail "xs and ys don't have the same length"
(3) Because the function is only well-defined for input of even length, the catch-all pattern _
matches the two-tuple containing lists where one is empty and the other isn't and raises an exception.
Upvotes: 1