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).
A monad transformer consists of:
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:
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 (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).