Monad transformer
This article relies largely or entirely on a single source. (November 2023) |
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
[edit | edit source]A monad transformer consists of:
- A type constructor
tof kind(* -> *) -> * -> * - Monad operations
returnandbind(or an equivalent formulation) for allt mwheremis 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 = returnlift (m `bind` k) = (lift m) `bind` (lift . k)
Examples
[edit | edit source]The option monad transformer
[edit | edit source]Given any monad , the option monad transformer (where denotes the option type) is defined by:
The exception monad transformer
[edit | edit source]Given any monad , the exception monad transformer (where E is the type of exceptions) is defined by:
The reader monad transformer
[edit | edit source]Given any monad , the reader monad transformer (where E is the environment type) is defined by:
The state monad transformer
[edit | edit source]Given any monad , the state monad transformer (where S is the state type) is defined by:
The writer monad transformer
[edit | edit source]Given any monad , the writer monad transformer (where W is endowed with a monoid operation ∗ with identity element ) is defined by:
The continuation monad transformer
[edit | edit source]Given any monad , the continuation monad transformer maps an arbitrary type R into functions of type , where R 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).
See also
[edit | edit source]References
[edit | edit source]- ^ Lua error in Module:Citation/CS1/Configuration at line 2172: attempt to index field '?' (a nil value).
External links
[edit | edit source]This section needs expansion. You can help by adding to it. (May 2008) |