2011-07-05 35 views
4

以下兩個功能不同的表現:模式與衛兵:否則不匹配?給定一個空字符串時

guardMatch [email protected](x:xs) 
    | x == '-'  = "negative " ++ xs 
    | otherwise  = l 

patternMatch ('-':xs) = "negative " ++ xs 
patternMatch l  = l 

這裏我的輸出:

*Main> guardMatch "" 
"*** Exception: matching.hs:(1,1)-(3,20): Non-exhaustive patterns in function guardMatch 

*Main> patternMatch "" 
"" 

問題:爲什麼不「否則」接近趕上空字符串?

回答

13

otherwise位於模式[email protected](x:xs)的範圍內,它只能匹配非空字符串。這可能有助於看看這是什麼(有效)轉換爲內部:(其實,我覺得if被轉換成case +後衛,而不是周圍的其他方法)

guardMatch l = case l of 
        (x :xs) -> if x == '-' then "negative " ++ xs else l 
patternMatch l = case l of 
        ('-':xs) ->     "negative " ++ xs 
        _  ->           l 

+0

IIRC按照你的說法翻譯'if'。 – fuz

+0

謝謝,這是有道理的。 –

9

一個後衛是總是在之後評估的模式。這是 - 如果模式成功,警衛就會嘗試。在你的情況下,模式(x:xs)排除空字符串,所以守衛甚至沒有嘗試,因爲模式失敗。

+0

謝謝。如果可以的話,我會接受這兩個答案。 –

3

另外兩個答案當然是完全正確的,但這裏有另一種思考方式:如果你寫了這個?

guardMatch [email protected](x:xs) 
    | x == '-'  = "negative " ++ xs 
    | otherwise  = [x] 

你認爲guardMatch ""是什麼?

+0

好點!正如上面的答案告訴我的,(x:xs)模式只匹配非空列表。 –

相關問題