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!
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-emptySo 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.