tags:

views:

101

answers:

1

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

+8  A: 

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

sepp2k
where do i look at original source code of this Monad.
Anton
@Anton: You can find it in the source for the [`Data.Maybe` module](http://haskell.org/ghc/docs/6.12.1/html/libraries/base-4.2.0.0/src/Data-Maybe.html), but the definition is simply `fail _ = Nothing`.
sepp2k
i did not find there pattern matching process. Only (Just x) >>= k = k x
Anton
i want to see source code which defines such behavior. Thanks.
Anton
@Anton: As my answer explained, there are two behaviours relevant here: a) In the `Maybe` monad `fail foo` returns `Nothing`. The source code that defines this behaviour is simply `fail _ = Nothing` in the instance declaration for `Monad Maybe`. b) A failed pattern match using `<-` calls `fail`. This behaviour is defined in [the Haskell standard](http://www.haskell.org/onlinereport/exps.html)'s section about translating `do` expressions.
sepp2k
@Anton: If you want to see the source code which implements the translation specified in the standard, you'll have to dig into the `ghc` source code (or the source code of whichever Haskell compiler you're using).
sepp2k
Thanks. The Haskell standard it is that i wanted. I found the next definition: do {p <- e; stmts} = let ok p = do {stmts} ok _ = fail "..." in e >>= ok
Anton