在阅读有关MonadPlus的Haskell Wikibook时,我发现以下函数基本上采用 a和 a并在此类 char 等于字符串头时返回,否则:Char
String
Just (char,tail)
Nothing
char :: Char -> String -> Maybe (Char, String)
char c s = do
let (c':s') = s
if c == c' then Just (c, s') else Nothing
他们解释说这let (c':s') = s
不会产生异常,因为它位于一个do
块中,该块将评估Nothing
模式何时失败,但是,事实并非如此,因为当我尝试它时:
*Main> char 'a' ""
*** Exception: exercice2.hs:5:7-17: Irrefutable pattern failed for pattern (c' : s')
所以我不得不将其重写为:
char' :: Char -> String -> Maybe (Char, String)
char' _ [] = Nothing
char' c (c':s')
| c == c' = Just (c,s')
| otherwise = Nothing
它按预期工作......为什么会发生在我身上?