Fth*_*der 6 haskell pattern-matching do-notation
在阅读关于MonadPlus的Haskell Wikibook时,我发现以下函数基本上采用a 和a 并且如果这样的char与字符串头相等则返回:CharStringJust (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
Run Code Online (Sandbox Code Playgroud)
并且他们解释说let (c':s') = s不会产生异常,因为它在一个do块中会评估Nothing模式何时失败,但事实并非如此,因为当我尝试它时:
*Main> char 'a' ""
*** Exception: exercice2.hs:5:7-17: Irrefutable pattern failed for pattern (c' : s')
Run Code Online (Sandbox Code Playgroud)
所以我不得不重写它:
char' :: Char -> String -> Maybe (Char, String)
char' _ [] = Nothing
char' c (c':s')
| c == c' = Just (c,s')
| otherwise = Nothing
Run Code Online (Sandbox Code Playgroud)
它按预期工作......为什么会发生在我身上?
我认为维基是错误的.他们可能会因为通过函数提供的绑定失败这一事实而混淆.所以下面的例子将使用函数from ,它返回:failMonadfailMaybeNothing
char :: Char -> String -> Maybe (Char, String)
char c s = do
(c':s') <- return s
if c == c' then Just (c, s') else Nothing
Run Code Online (Sandbox Code Playgroud)