[Haskell-cafe] Do expression definition

Ben Millwood haskell at benmachine.co.uk
Mon Sep 13 07:54:59 EDT 2010

On Mon, Sep 13, 2010 at 8:21 AM, Alexander Kotelnikov <sacha at myxomop.com> wrote:
> And, also, would it make any difference if
> do {p <- e; stmts}      =       let ok p = do {stmts}
>    ok _ = fail "..."
>  in e >>= ok
> is redefined as "e >>= (\p -> do {stmts})"?

This is the magic that allows pattern-match failure in a do expression
to return a normal result. Notice that "fail" and not "error" is
called - each Monad has its own fail method, so that for example:

uncons :: [a] -> Maybe (a, [a])
uncons xs = do { (x:xs) <- return xs; return (x, xs) }

evaluates to Nothing rather than causing an exception when xs is empty.

That this implementation detail ends up in the Monad class is regarded
by many as untidy, though.

More information about the Haskell-Cafe mailing list