Monad transformer


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.

Definition

A monad transformer consists of:
  1. A type constructor t of kind -> * -> *
  2. Monad operations return and bind for all t m where m is a monad, satisfying the monad laws
  3. An additional operation, lift :: m a -> t m a, satisfying the following laws: :
  4. # lift. return = return
  5. # lift = `bind`

    Examples

The option monad transformer

Given any monad, the option monad transformer is defined by:

The exception monad transformer

Given any monad, the exception monad transformer is defined by:

The reader monad transformer

Given any monad, the reader monad transformer is defined by:

The state monad transformer

Given any monad, the state monad transformer is defined by:

The writer monad transformer

Given any monad, the writer monad transformer is defined by:

The continuation monad transformer

Given any monad, the continuation monad transformer maps an arbitrary type into functions of type, where is the result type of the continuation. It is defined by:
Note that monad transformations are usually not commutative: for instance, applying the state transformer to the option monad yields a type , whereas the converse transformation has type .