In functional programming, a monad transformer is a type constructor which takes a monad as an argument and returns a monad as a result.
Monad transformers can be used to compose features encapsulated by monads - such as state, exception handling, and I/O - in a modular way. Typically, a monad transformer is created by generalising an existing monad; applying the resulting monad transformer to the identity monad yields a monad which is equivalent to the original monad (ignoring any necessary boxing and unboxing).
Definition
A monad transformer consists of:
- A type constructor
t
of kind (* -> *) -> * -> *
- Monad operations
return
and bind
(or an equivalent formulation) for all t m
where m
is a monad, satisfying the monad laws
- An additional operation,
lift :: m a -> t m a
, satisfying the following laws:[1] (the notation `bind`
below indicates infix application):
lift . return = return
lift (m `bind` k) = (lift m) `bind` (lift . k)
Examples
Given any monad
, the option monad transformer
(where
denotes the option type) is defined by:



Given any monad
, the exception monad transformer
(where
is the type of exceptions) is defined by:



Given any monad
, the reader monad transformer
(where
is the environment type) is defined by:



Given any monad
, the state monad transformer
(where
is the state type) is defined by:



Given any monad
, the writer monad transformer
(where
is endowed with a monoid operation
with identity element
) is defined by:



Note that monad transformations are not commutative: for instance, applying the state transformer to the option monad yields a type
(a computation which may fail and yield no final state), whereas the converse transformation has type
(a computation which yields a final state and an optional return value).
See also
References
External links
- [1] - a highly technical blog post briefly reviewing some of the literature on monad transformers and related concepts, with a focus on categorical-theoretic treatment
![[icon]](/media/wikipedia/commons/thumb/1/1c/Wiki_letter_w_cropped.svg/20px-Wiki_letter_w_cropped.svg.png) | This section needs expansion. You can help by adding to it. (May 2008) |