2 ms·
All Applicatives have those two variants, not just Applicatives which are also Monads. There is a Backwards newtype in Control.Applicative.Backwards which rever
by nybble41 8y ago
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 <*> f