为什么模式匹配不会在Maybe monad中抛出异常

Ant*_*ton 8 monads haskell exception

我的问题很简单.为什么错误的模式匹配不会在Maybe monad中抛出异常.为清楚起见:

data Task = HTTPTask {
 getParams   ::  [B.ByteString],
 postParams  ::  [B.ByteString],
 rawPostData ::  B.ByteString 
}  deriving (Show)

tryConstuctHTTPTask :: B.ByteString -> Maybe Task
tryConstuctHTTPTask str = do
 case decode str of
    Left _  -> fail ""
    Right (Object trie) -> do
        Object getP    <- DT.lookup (pack "getParams")   trie
        Object postP   <- DT.lookup (pack "postParams")  trie
        String rawData <- DT.lookup (pack "rawPostData") trie
        return $ HTTPTask [] [] rawData
Run Code Online (Sandbox Code Playgroud)

看看tryConstuctHTTPTask函数.我认为当模式不匹配时(例如" Object getP ")我们必须得到类似" Prelude.Exception "的东西,而不是我得到的" Nothing ".我喜欢这种行为,但我不明白为什么.

谢谢.

sep*_*p2k 14

这样做pattern <- expressiondo-块,将调用fail时模式不匹配.所以它等同于做

expression >>= \x ->
case x of
  pattern -> ...
  _ -> fail
Run Code Online (Sandbox Code Playgroud)

由于在monad中fail定义Nothing,因此使用的是失败的模式匹配.MaybeNothing<-

  • @Anton:正如我的回答所解释的,这里有两个相关的行为:a)在`Maybe` monad`fail foo`中返回`Nothing`.定义此行为的源代码只是`Monad Maybe`的实例声明中的`fail _ = Nothing`.b)使用`<-`调用`fail`失败的模式匹配.这种行为在[Haskell标准](http://www.haskell.org/onlinereport/exps.html)关于翻译`do`表达式的部分中定义. (4认同)