4 ms·
Does this mean that many Monads have two possible Applicative instances? For the two orders of "running" mf and ma?
by taejo 8y ago
Does 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