3 ms·
Right It is interesting that he knew this fact,and that it would be nice if this code could be automatically derived too, but I think that should not replace t
by platz 8y ago
Right
It is interesting that he knew this fact,and that it would be nice if this code could be automatically derived too, but I think that should not replace the learning process.
It is more of a nit for advanced users
- nybble41 8y agoIndeed, the learning process is important. I think it's particularly instructive to look at how `ap` is implemented, and what is left out in the transition from Monad to Applicative: mf `ap` ma = do f <- mf a <- ma return (f a) With a Monad, the action on the right of the bind operator is a function of the result of the action on the left. The second operand of the `ap` function, however, does not have any access to the result of the first operand. The two operands are evaluated independently, apart from their side-effects. That reflects the fundamental difference between Applicative and Monad: an Applicative instance just sequences effects and combines results, whereas a Monad instance allows effects to depend on previous results.
- taejo 8y agoDoes this mean that many Monads have two possible Applicative instances? For the two orders of "running" mf and ma?
- lmm 8y agoI don't know about "many", but certainly some - e.g. you could form a "reversed MonadWriter" applicative that would write the messages from ma before the messages from mf. For a lot of monads the effects are commutative though, in which case the "two possible" Applicatives are actually the same, e.g. Maybe obviously behaves the same whichever order you "run" mf and ma in.
- taejo 8y agoMy "many" exactly meant to exclude the commutative case :)
- nybble41 8y agoAll Applicatives have those two variants, not just Applicatives which are also Monads. There is a Backwards newtype in Control.Applicative.Backwards which reverses the order of effects for any Applicative: GHCi> import Control.Applicative.Backwards GHCi> :i Backwards newtype Backwards (f :: k -> *) (a :: k) = Backwards {forwards :: f a} GHCi> forwards $ (++) <$> Backwards ("foo" <$ print 1) <*> Backwards ("bar" <$ print 2) 2 1 "foobar" As you can see, the result is the same but the effects are reversed. The definition is simple: instance Applicative f => Applicative (Backwards f) where pure = Backwards . pure Backwards f <*> Backwards a = Backwards $ (flip ($)) <$> a <*> f