I am currently studying the bonds between monad and applicative functors.
I see two implementation for ap:
ap m1 m2 = do { f <- m1 ; x <- m2 ; return (f x) }
and
ap m1 m2 = do { x <- m2 ; f <- m1 ; return (f x) }
The second one is different, yet, would it be a good implementation for <*>
?
I got lost in the proof of pure (.) <*> u <*> v <*> w = u <*> (v <*> w)
I try to get an intuition of "what part of the monad is the applicative functor"...
There are at least three relevant aspects to this question.
Given a
Monad m
instance, what is the specification of its necessaryApplicative m
superclass instance? Answer:pure
isreturn
,<*>
isap
, soNote that this specification is not a law of the
Applicative
class. It's a requirement onMonad
s, to ensure consistent usage patterns.Given that specification (by candidate implementation), is
ap
the only acceptable implementation. Answer: resoundingly, no. The value dependency permitted by the type of>>=
can sometimes lead to inefficient execution: there are situations where<*>
can be made more efficient thanap
because you don't need to wait for the first computation to finish before you can tell what the second computation is. The "applicative do" notation exists exactly to exploit this possibility.Do any other candidate instances for
Applicative
satisfy theApplicative
laws, even though they disagree with the requiredap
instances? Answer: yes. The "backwards" instance proposed by the question is just such a thing. Indeed, as another answer observes, any applicative can be turned backwards, and the result is often a different beast.For a further example and exercise for the reader, note that nonempty lists are monadic in the way familiar from ordinary lists.
Find at least four behaviourally distinct instances of
Applicative Nellist
which obey the applicative laws.Let's start with the obvious fact: such a definition for
<*>
violates theap
-law in the sense that<*>
shouldap
, whereap
is the one defined in theMonad
class, i.e. the first one you posted.Trivialities aside, as far as I can see, the other applicative laws should hold.
More concretely, let's focus on the composition law you mentioned. Your "reversed"
ap
can also be defined as
where
<*>
is the "regular"ap
.This means that, for instance,
(I hope I got everything OK)
Try doing something similar to the left hand side.