2011-10-04 56 views
7
test :: String -> String -> Int 

test' x y n = n 
test' "" (y:ys) n = error "error" 
test' (x:xs) "" n = error "error" 
test' (x:xs) (y:ys) n = 
     if  x == y 
     then test' xs ys n 
     else test' xs ys (n+1) 
test a b = test' a b 0 

當我編譯,我得到這樣的輸出:哈斯克爾 - 模式匹配(ES)重疊

Warning: Pattern match(es) are overlapped 

得到的答覆永遠是「0」,這是不是我的本意。代碼有什麼問題以及如何解決它?

回答

9

test' x y n = n會匹配每個呼叫,其他模式將不被考慮。我認爲這種情況應該是test' "" "" n = n。如果您將原始行移動到末尾(當所有其他情況都失敗時),您會得到相同的結果,但是您應該編寫test' _ _ n = n,這表明您故意忽略某些參數。

[編輯]

較短的解決辦法是:

test a b | length a == length b = sum $ map fromEnum $ zipWith (/=) a b 
     | otherwise = error "error" 

zipWith表達產生的Bool列表這是True每差。功能fromEnumFalse映射到0True1

+0

非常有幫助!我學到了很多!謝謝 – Ferry

7

模式按順序嘗試。 test'的第一個模式始終匹配,因此總是使用該情況。第一種情況應該可能是

test' "" "" n = n 

改爲。