\begin{xy} \xymatrix{ T \ar[d]_{\eta T} \ar[r]^{T\eta} \ar@{=}[dr] & TT \ar[d]^{\mu} \\ TT \ar[r]_{\mu} & T } \end{xy}
We can also write down the natural transformations in terms of their components. For each object A of C, the unit is a morphism ηA:A→TA, and the multiplication is a morphism μA:T(TA)→TA, such that the following diagrams commute:
\begin{xy} \xymatrix{ TA \ar[d]_{\eta TA} \ar[r]^{T\eta{(A)}} \ar@{=}[dr] & T(TA) \ar[d]^{\mu{A}} \\ T(TA) \ar[r]_{\mu{A}} & TA } \end{xy}
An application of this concept is that monads provide a way to express computations (in terms of morphisms) that include additional structure or side-effects (captured by the endofunctor T) in such a way that these computations can be chained together (via the μ natural transformation) and lifted over the monadic structure (via the η natural transformation), and they do so in a way that is consistent (respecting the associativity and unit laws).
Example
The Monad, by definition, requires us to implement two functions: the unit, which is called return in Haskell, where we just have to lift a value into the Monad (e.g., put a value into a list), and the multiplication join.
Haskell Definition of Monad (Interface)
These have to obey the Monad laws:
We can now draw the commutative diagram for the Haskell definition of Monad:
The definition of a monad given here is equivalent to the one we typically use in Haskell.
We can easily define >>= with join and fmap.
This operation is called bind (or is sometimes refered to as flatMap). The bind function can be used if you need to operate on the lifted value before collapsing. We can also translate the other way around and define join in terms of >>= and id:
Hence join is bind applied to the identity function. These two constructions are reverse to each other and they translate the monad laws correctly. Now we lets have a look at some concrete examples (instances of Monad).
An Instance of Monad, the List Monad
Another Instance, the Maybe Monad
All of the above is already implemented in the standard Haskell library, so you can simply open an interactive Haskell interpreter (ghci) and test the following examples.
References
0.The diagram displayed at the top of this post is a modified version of Brent Yorgey's Typeclassopedia diagram ↩