简体   繁体   English

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

[英]Why pattern matching does not throw exception in Maybe monad

My question is simple. 我的问题很简单。 Why wrong pattern matching does not throw exception in Maybe monad. 为什么错误的模式匹配不会在Maybe monad中抛出异常。 For clarity : 为清楚起见:

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

Look at tryConstuctHTTPTask function. 看看tryConstuctHTTPTask函数。 I think that when the pattern does not match (for example " Object getP ") we must get something like " Prelude.Exception ", instead i get the " Nothing ". 我认为当模式不匹配时(例如“ Object getP ”)我们必须得到类似“ Prelude.Exception ”的东西,而不是我得到的“ Nothing ”。 I like this behavior but i am not understand why. 我喜欢这种行为,但我不明白为什么。

Thanks. 谢谢。

Doing pattern <- expression in a do -block, will call fail when the pattern does not match. do -block中执行pattern <- expression ,当模式不匹配时将调用fail So it is equivalent to doing 所以它等同于做

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

Since fail is defined as Nothing in the Maybe monad, you get Nothing for failed pattern matches using <- . 由于在Maybe monad中将fail定义为Nothing ,因此使用<-来获取失败模式匹配的Nothing

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM