Applicative functors and actions

This is obvious and all, but it suddenly clicked why you can’t choose different paths inside of Applicative. What I mean is that things of this form aren’t possible:

something = do p' <- getABool
               if p then putStrLn "it was true"
                    else putStrLn "it wasn't"

However, I couldn’t think why. Well, the reason is that the methods of Applicative are pure and (<*>) (obviously), which are like return and ap (also obviously). But! Note that with (<*>) (and ap) you can only work inside the functor:

mf `ap` mx ≡ mf >>= \f -> mx >>= \x -> f x

On other words, you would have to evaluate both x and y in something, somewhat like this:

something' p x y = do p' <- p
                      x' <- x
                      y' <- y
                      return (if p then x' else y')
 
-- or
somethingA p x y = f <$> p <*> x <*> y
    where f p x y = if p then x else y

…evaluating both x and y and (in IO) performing both their side effects.

I’m sure this explanation is terrible, but it helped me at least?

Leave a Reply

You must be logged in to post a comment.