0

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);

glennsl
  • 28,186
  • 12
  • 57
  • 75
  • From the [help/on-topic]: *3. Questions asking for homework help must include a summary of the work you've done so far to solve the problem, and __a description of the difficulty you are having solving it.__* – glennsl Nov 15 '17 at 06:22
  • The type signature that you give ( `alternate : 'a list -> 'a list` ) doesn't match the rest of the question (which seems to be about (`alternate : 'a list * 'a list -> 'a list`). In any event, here is a hint: the recursive case can involve the swapping of the order of the two arguments so what plays the role of `x` in one call will play the role of `y` in the next, and vice-versa. – John Coleman Nov 15 '17 at 16:47

1 Answers1

1

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.

sshine
  • 15,635
  • 1
  • 41
  • 66