Re:Applicative WTF?
by taejo on Wednesday October 24, 2018 @08:06AM
(#18291664)
Does this mean that many Monads have two possible Applicative instances? For the two orders of "running" mf and ma?
[ Parent
| on HN ]
All 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 <*> fI 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.