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

时间:2010-10-30 13:12:23

标签: exception haskell monads

我的问题很简单。为什么错误的模式匹配不会在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

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

感谢。

1 个答案:

答案 0 :(得分:13)

pattern <- expression - 块中执行do,当模式不匹配时,将调用fail。所以它相当于做

expression >>= \x ->
case x of
  pattern -> ...
  _ -> fail

由于fail monad中的Nothing被定义为Maybe,因此使用Nothing获取<-失败的模式匹配。