简体   繁体   中英

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. 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. 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 ". 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. 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 <- .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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