[Haskell-cafe] Applicative and Monad transformers
Ralf Hinze
ralf.hinze at comlab.ox.ac.uk
Thu Aug 27 01:48:39 EDT 2009
Hi Jeremy,
> I have seen it said that all Monads are Applicative Functors because
> you can just do:
>
> instance (Monad f, Applicative f) => Applicative (ReaderT r f) where
> pure = return
> (<*>) = ap
>
> However, that instance for ReaderT does not exhibit the properties I
> was hoping for.
OK, let's calculate. Here are the necessary definitions for the reader
monad (not the monad transformer).
m >>= k = \ x -> k (m x) x
u <*> v = \ x -> (u x) (v x)
return a = pure a = \ x -> a
So, <*> is the S combinator and pure is the K combinator.
u >>= \ f -> v >>= \ a -> return (f a)
= { definition of >>= }
\ x -> (\ f -> v >>= \ a -> return (f a)) (u x) x
= { beta }
\ x -> (v >>= \ a -> return ((u x) a)) x
= { definition of >>= }
\ x -> (\ a -> return ((u x) a)) (v x) x
= { beta }
\ x -> return ((u x) (v x)) x
= { definition of return }
\ x -> (u x) (v x)
= { definition of <*> }
u <*> v
Yes, both definitions are, in fact, equal.
So, what went wrong in your program? Observe that the first instance
declaration can be simplified to
instance (Monad f) => Applicative (ReaderT r f) where
pure = return
(<*>) = ap
which is suspicious.
Hope this helps, Ralf
More information about the Haskell-Cafe
mailing list