Prev: Monad transformers | TOC: Contents | Next: Anatomy of a monad transformer |
Haskell's base libraries provide support for monad transformers in the form of classes which represent monad transformers and special transformer versions of standard monads.
The MonadTrans
class is defined in
Control.Monad.Trans
and provides the single function lift
. The lift
function
lifts a monadic computation in the inner monad into the combined monad.
class MonadTrans t where lift :: (Monad m) => m a -> t m a |
Monads which provide optimized support for lifting IO operations
are defined as members of the MonadIO
class, which defines
the liftIO
function.
class (Monad m) => MonadIO m where liftIO :: IO a -> m a |
The standard monads of the monad template library all have transformer versions
which are defined consistently with their non-transformer versions.
However, it is not the case the all monad transformers apply the same
transformation. We have seen that the ContT
transformer
turns continuations of the form (a->r)->r
into continuations
of the form (a->m r)->m r
. The StateT
transformer is different. It turns state transformer functions of
the form s->(a,s)
into state transformer functions of the
form s->m (a,s)
. In general, there is no magic formula
to create a transformer version of a monad — the form of each transformer
depends on what makes sense in the context of its non-transformer type.
Standard Monad | Transformer Version | Original Type | Combined Type |
---|---|---|---|
Error | ErrorT | Either e a |
m (Either e a) |
State | StateT | s -> (a,s) |
s -> m (a,s) |
Reader | ReaderT | r -> a |
r -> m a |
Writer | WriterT | (a,w) |
m (a,w) |
Cont | ContT | (a -> r) -> r |
(a -> m r) -> m r |
Order is important when combining monads.
StateT s (Error e)
is different than
ErrorT e (State s)
. The first produces a combined
type of s -> Error e (a,s)
, in which the
computation can either return a new state or generate an error.
The second combination produces a combined type of
s -> (Error e a,s)
, in which the computation
always returns a new state, and the value can be an error or a normal value.
Prev: Standard monad transformers | TOC: Contents | Next: Anatomy of a monad transformer |