Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 292
Anton Avatar asked Oct 30 '10 13:10

Anton


1 Answers

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

like image 87
sepp2k Avatar answered Sep 17 '22 15:09

sepp2k