[Haskell-cafe] Monad m => m (Maybe a) -> m (Maybe a) -> m (Maybe a)

Chris Wong lambda.fairy at gmail.com
Thu Nov 13 00:23:20 UTC 2014

On Thu, Nov 13, 2014 at 11:07 AM, Andras Slemmer <0slemi0 at gmail.com> wrote:
> Well, "try" is really doing two things: chaining Maybes, and then adding a
> monadic context:
> try :: Monad m => m (Maybe a) -> m (Maybe a) -> m (Maybe a)
> try = liftM2 (<|>)
> (You could weaken the assumption by using (Applicative m) instead)

That's different to Evan's original function.

Evan's solution short-circuits: it does not execute the second action
if the first succeeds. But your one runs both actions unconditionally.

For example, the expression

    try (return $ Just ()) (putStrLn "second action executed" >> return Nothing)

outputs "second action executed" with your solution, but not with Evan's.

The lesson is, applicative and monadic composition don't always yield
the same results.


More information about the Haskell-Cafe mailing list