Why pattern matching doesn't throw an exception in Maybe monad

My question is simple. Why pattern matching does not throw an 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 

Take a look at the tryConstuctHTTPTask function. I think that when the template does not match (for example, "Object getP"), we should get something like "Prelude.Exception", instead we will get "Nothing". I like this behavior, but I don’t understand why.

Thanks.

+7
exception haskell monads
source share
1 answer

Executing pattern <- expression in the do block will fail if the pattern does not match. So this is equivalent to doing

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

Since fail defined as Nothing in the Maybe monad, you get Nothing for failed pattern matches with <- .

+11
source share

All Articles