More monads
Besides Maybe
and State
, a number of other applicative functor examples we saw in the previous chapter also have a monad structure. We revisit them here.
The Identity monad
Our first example is the Identity
functor, which models pure computations. Its monad instance provides a sequential notation for function application:
Control.Monad.Identity
instance Monad Identity where
Identity x >>= f = f x
When emphasizing the monad structure, this type is usually called the Identity
monad rather than the Identity
functor.
Instead of writing a nested function application f (g (h x))
, we can write this in successive steps as Identity
(f x) >>= (Identity . g) >>= (Identity . h)
. This isn’t particularly convenient, but it looks a bit more familiar to imperative programmers when we use the do
notation (and ignore the Identity
wrappers):
do y <- Identity (f x) z <- Identity (g y) Identity ...