0

From what I've learned,

fun addX (X, []) = []
 |  addX (X, y::ys) = (X + y :: addX(X, ys));

works perfectly fine, but when I try to multiply list1 by list2 with this method, it's giving me "Warning: match nonexhaustive", here's my code:

fun multList ([], []) = []
 |  multList (x::xs, y::ys) = (x * y :: multList(xs, ys));

Which part did I do wrong? any help appreciated, thank you!

ymonad
  • 11,710
  • 1
  • 38
  • 49
chenchen
  • 49
  • 3
  • 6

1 Answers1

4

Since x::xs and y::ys matches "non-empty list", your current code is matching the pattern only for:

  • ([],[]) ... both list are empty
  • (x::xs,y::ys) .. both list are non-empty

So you should consider the case "one list is empty, and the another list is non-empty".

The following is the example code which does not show the warning.

fun
  multiList ([],[]) = []
  | multiList (X,[]) = X
  | multiList ([],X) = X
  | multiList (x::xs, y::ys) = (x*y ::multiList(xs,ys));

This code returns the non-empty one when either of the list is empty.

Edit: As @ruakh says in the comment, the following code is better since it seems natural behavior for multiList, but I would leave the above code for explanation.

fun
  multiList ([],[]) = []
  | multiList (x::xs, y::ys) = (x*y ::multiList(xs,ys))
  | multiList _ = raise Fail "lists of non equal length";

Note that _ is wildcard, so it matches anything when neither ([],[]) nor (x::xs,y::ys) matches.

ymonad
  • 11,710
  • 1
  • 38
  • 49
  • +1, though I suspect the intended behavior is something actually like `| multiList _ => raise Fail "lists of non-equal length"`. – ruakh Nov 14 '16 at 07:19
  • thank you sir! I just made `| multiList (X,[]) = raise DifferentLength | multiList ([],X) = raise DifferentLength`, which raises a similar exception – chenchen Nov 14 '16 at 07:50