2016-11-14 57 views
0

從我瞭解到,乘以列表1的列表2,收到「警告:符合非排他性」

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

工作完全正常,但是當我試圖通過列表2用此方法繁殖列表1,這是給我「警告:match nonxhaustive「,這裏是我的代碼:

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

哪部分我做錯了?任何幫助表示感謝,謝謝!

回答

4

由於x::xsy::ys比賽「非空列表」,當前的代碼,只是爲了匹配模式:

  • ([],[]) ...兩個列表是空的
  • (x::xs,y::ys) ..兩個列表都是非 - 空

所以你應該考慮「一個列表是空的,另一個列表是非空的」的情況。

以下是不顯示警告的示例代碼。

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

此代碼返回非空的列表,當其中任何一個列表爲空時。

編輯:作爲@ruakh的評論說,下面的代碼是更好,因爲它似乎爲multiList自然的行爲,但我會離開上面的代碼解釋。

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

注意_是通配符,因此它匹配任何東西既不([],[])也不(x::xs,y::ys)匹配時。

+0

+1,但我懷疑預期的行爲實際上是''| multiList _ =>提高失敗「列表的非等長」'。 – ruakh

+0

謝謝先生!我只是做了'| multiList(X,[])= raise DifferentLength | multiList([],X)= raise DifferentLength',這引發了一個類似的異常 – chenchen