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

Francesco Mazzoli f at mazzo.li
Thu Nov 13 10:08:16 UTC 2014


On 13 November 2014 01:23, Chris Wong <lambda.fairy at gmail.com> wrote:
> 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.

Applicative and monadic composition *should* be the same, given that
Applicative contains the law

    (<*>) = ap

And in fact if we rewrite Andras solution as

    try a b = (<|>) <$> a <*> b

It is still broken.

The fact that you find libraries where (<*>) is not ap has been
confusing for me as well :P.

Evan's `try` doesn't use Applicative at all, but short-circuits
manually.  For this kind of stuff I usually use MaybeT.

Francesco


More information about the Haskell-Cafe mailing list