⇐ back to writing
This is an introduction to the formal structure called a monad. It is not a paper on the many other definitions of monads, such as the Pythagorean monad or Leibniz's metaphysical concept. Nor is it about isolated mountains: a monadnock.
The structure we exposit is algebraic and sees vast applications in category theory and functional programming. Unfortunately, for a structure such as a monad (in the context of category theory at least) it is nigh impossible to get a grasp of its nature without first having a decent understanding of category theory itself. What follows then is my best attempt to lay out necessary prerequisites and a direct path to the definition of a monad on a category \(\mathcal C\). The following post is dense; I will not shy away from technical details in the hope of avoiding the "monad tutorial fallacy". We then examine monads in the context of functional programming and compare the two different faces of monads. Lastly, we conclude with a presentation of a monad outside of either context: to model indefinites in natural language semantics (Charlow 2020).
We will assume the reader has some familiarity with category theory, thus we exercise brevity. For the categorically confused, I suggest Riehl's Category theory in context or Awodey's Category Theory.
A category \(\mathcal C\) consists of a collection of objects and a collection of morphisms satisfying the following properties:
A functor \(F : \mathcal C \to \mathcal D\) is a map between categories such that following properties hold,
Given two categories \(\mathcal C\) and \(\mathcal D\) and two functors between them \(F,G : \mathcal C \rightrightarrows \mathcal D\). A natural transformation \(\alpha: F \Rightarrow G\) consists of morphisms called components \(\alpha_c : Fc \to Gc\), for each object \(c\) in \(\mathcal C\), such that for any morphism \(f\) in \(\mathcal C\), the following diagram commutes.
We sometimes draw the fun picture.
A monoid object \(M\) in a category \(\mathcal{C}\) consists of a morphisms \(\theta : M \otimes M \to M\) and \(\eta : I \to M\), where \(I\) is a unit object, such that the following diagrams commute¹.
The left diagram expresses that \(\theta\) is associative and the right diagram expresses that \(\eta\) is a right and left unit. If we take \(\mathcal{C}=\mathcal{Set}\), then we indeed get back the familiar algebraic structure.
As another example, let \(\mathbb k\) be a field. A monoidal vector space is a \(\mathbb k\)-algebra. Let \(\mathcal{Vect}_{\mathbb k}\), be the category of vector spaces with field of scalars \(\mathbb k\). A monoid in \(\mathcal Vect _{\mathbb k}\) is a vector space \(V\) together with the tensor product \(\otimes : V \otimes V \to V\) and unit \(\eta : \mathbb k \to V\).
This coincides with the notion that a \(\mathbb k\)-algebra is a vector space where we also can multiply vectors.
Given any two categories² \(\mathcal{C}\) and \(\mathcal{D}\) we may form another category \(\mathcal{D}^{\mathcal{C}}\) called the functor category. Note that this notation is reminiscent of the set of functions \(Y^X\) between two sets \(X\) and \(Y\). The objects of our new category \(\mathcal D ^{\mathcal C}\) are functors \(F:\mathcal C \to \mathcal{D}\). The morphisms are natural transformations, \(\alpha : F \Rightarrow G\) for functors \(F, G\) in \(\mathcal D ^{\mathcal C}\). We leave it to the reader to confirm the category axioms.
An endofunctor is a functor \(F:\mathcal C \to \mathcal C\). Thus for any (small) category \(\mathcal C\), we have the endofunctor category \(\mathcal C^{\mathcal C}\), whose objects are endofunctors \(F:\mathcal C \to \mathcal C\) and whose morphisms are natural transformations.
A monad (on \(\mathcal C\)) is a triple \((T, \theta, \eta)\) where \(T:\mathcal C \to \mathcal C\) and \(\theta : T \circ T \Rightarrow T\) and \(\eta : 1_{\mathcal C} \Rightarrow T\) are natural transformations³ (here \(1\) is the identity functor on \(\mathcal{C}\)) so that the following diagrams commute.
If we compare these declarations and diagrams to the previous sections we see that a monad really is a monoid object in the category of endofunctors \(\mathcal C^{\mathcal C}\). We take multiplication \(\theta\) to be the obvious choice of composition of functors.
As discussed here, if we take our multiplication to be something other than the composition of functors we aren’t guaranteed a monad. Copular clauses are ambiguous, to say that "a monad is just a monoid in the category of endofunctors" is to offer a particular instance of a monoid object in the endofunctor category, it is not the definition of a monad.
Recall that an adjunction between categories \(\mathcal C\) and \(\mathcal D\) is a pair of functors \(F:\mathcal C \rightleftarrows \mathcal D : G\) with natural transformations \(\eta : 1 \Rightarrow GF\) and \(\epsilon : FG \Rightarrow 1\) satisfying the triangle identities.
Observe that \(GF\) is an endofunctor on \(\mathcal C\) and that \(\eta : 1 \Rightarrow GF\) looks quite familiar. If multiplication is defined via whiskering \(\theta = G \epsilon F\), then indeed it is the case that we arrive at a monad,⁴ since the monoid diagrams commute from the adjunction triangle inequalities and naturality.
An adjoint pair is one of the most important concepts in category theory, we can see why monads appear so often and why they are valuable to study.
Pure functional languages offer functions that are purely mathematical, examples include Miranda, Haskell, and Lean. Some impure functional languages are ML and Lisp dialects.
Monads offer a way for pure languages to mimic imperative features like effects, state, and non-determinism. We begin by presenting the maybe monad as our first example, which is used when constructing a function that may crash. This example follows Wadler (1997) with some minor alterations to the code. The samples will be in Haskell.
Suppose we are writing a simple evaluator for dividing two terms where terms are constructed from the division of integers.
data Term = Con Int | Div Term Term
good, bad :: Term
good = (Div (Div (Con 54) (Con 6)) (Con 3))
bad = (Div (Con 3) (Con 0))
Suppose we are naive, or perhaps lazy, and write the following evaluator.
eval0 :: Term -> Int
eval0 (Con a) = a
eval0 (Div t u) = eval0 t `div` eval0 u
If we run eval0 good we will have no problem and eval0 good will compute 3. However, eval0 bad will crash our program. This is because we have no way of handling divide by zero errors. In an impure language, fixing this is relatively easy. In Haskell we're going to need something more complex.
Below is our next evaluator where we introduce a type constructor M and define a type M a that has two constructors Throw and Return. The evaluator will either throw a divide by zero error or it will simply compute and return the result as intended.
data M a = Throw Exception | Return a
type Exception = String
eval1 :: Term -> M Int
eval1 (Con a) = Return a
eval1 (Div t u) = case eval1 t of
Throw e -> Throw e
Return a ->
case eval1 u of
Throw e -> Throw e
Return b ->
if b == 0
then Throw "divide by zero"
else Return (a `div` b)
The type constructor M has the underlying structure of a monad. Our second evaluator eval1 works as intended but it's difficult to read (it literally goes off the page in mobile view). Luckily, a defining characteristic of Haskell is its implementation of monads and the syntactic sugar of do.
Maybe is implemented like so.
data Maybe a = Nothing | Just a
Now let's use Maybe to write a new evaluator.
eval2 :: Term -> Maybe Int
eval2 (Con a) = Just a
eval2 (Div t u) = case eval2 t of
Nothing -> Nothing
Just a ->
case eval2 u of
Nothing -> Nothing
Just b ->
if b == 0
then Nothing
else Just (a `div` b)
Nothing really changed except now we don't get a particular error. We can write this much nicer using do.
eval3 :: Term -> Maybe Int
eval3 (Con a) = Just a
eval3 (Div t u) = do
a <- eval3 t
b <- eval3 u
if b == 0
then Nothing
else Just (a `div` b)
At this iteration our evaluator is up to par.
We presented only one monad (although we will see the list monad later) and we will move on to the abstract definition. For more examples such as state and output monads see Wadler (1997) or see Haskell wiki for the implementations of these based off the same paper.
A monad is a type constructor \(\textsf M\) together with two functions \(\textsf{unit}: \textsf a \to \textsf{M} \space \textsf a\)⁵ and \(\texttt{>>=}: \textsf M \space \textsf a \to (\textsf a \to \textsf M \space \textsf b) \to \textsf M \space \textsf b\) called "bind". Together, these functions satisfy the following equations,
To concretize, Maybe's \(\textsf{unit}\) is Just and \(\texttt{>>=}\) is
(>>=) m f = case m of
Nothing -> Nothing
Just x -> f x
which we saw in the structure of the previous evaluators.
While our two definitions of a monad look similar, unfortunately, they are not identical. We will spend sometime examining how the two constructions differ. We will take a less than rigorous approach and conclude by appreciating a single monad, namely the list monad, in both contexts.
First off, let's observe both definitions. We distinguish the two contexts by varying the typeface; the category theoretic monad will use \(\text{Computer Modern}\) in math mode, whereas monads in the context of functional programming will use \(\textsf{Computer Modern Sans Serif}\). Moreover, we tend to the notational conventions of category theory; namely, action of a functor \(F\) on objects and morphisms are both denoted by juxtaposition, i.e. \(Fc\) and \(Ff\).
A monad consists of the following data,
satisfying the monoid diagrams.
A \(\textsf{monad}\) consists of the following data,
Perhaps the first question is how are \(M\) and \(\textsf M\) related? For \(M\), we take an object \(a\) in \(\mathcal C\) and return another object \(Ma\). Analogously, given a type \(\textsf a\), we get back a type \(\textsf{Ma}\). For an object \(a\) in \(\mathcal C\) there is morphism \(\eta_a: a \to Ma\) given by the component of the natural transformation \(\eta\). The morphism \(\eta_a: a \to Ma\) clearly corresponds to \(\textsf{unit}: \textsf a \to \textsf{M} \textsf a\). Unfortunately, the similarities end there, \(\mu\) and \(\texttt{>>=}\) look nothing alike. Let's see if we can massage \(\texttt{>>=}\) into something that looks like \(\mu\). Similar to what had happened with \(\textsf{unit}\), we really only need to define a component of \(\mu\) for an arbitrary \(a\). This means we are looking for a function of type \(\textsf{MMa} \to \textsf{Ma}\).
Suppose we have \(\textsf x : \textsf{Ma}\) and \(\textsf{id}_{\textsf M \textsf a} : \textsf{Ma} \to \textsf{Ma}\), then consider, \begin{align} \textsf{unit}\space \textsf x &: \textsf{MMa} \\ \textsf{unit}\space \textsf x \space\texttt{>>=} &: (\textsf{Ma} \to \textsf{Mb}) \to \textsf{Mb} \\ \textsf{unit}\space \textsf x \space\texttt{>>=}\space \textsf{id}_{\textsf{Ma}} &: \textsf{Ma} \end{align}
If we abstract over \(\textsf x\). We get the function, \[\lambda \textsf x.(\textsf{unit} \space \textsf x \space \texttt{>>=} \space \textsf{id}_{\textsf{Ma}}) : \textsf{MMa} \to \textsf{Ma},\] which has the type we are looking for. This function is usually called \(\textsf{join}\). We can also derive \(\texttt{>>=}\) from \(\textsf{join}\). Let \(\textsf x : \textsf{Ma}\) and \(\textsf f : \textsf a \to \textsf{Mb}\) be arbitrary. Observe⁶ the following terms, \begin{align} \textsf{Mf} &: \textsf{Ma} \to \textsf{MMb} \\ \textsf{Mfx} &: \textsf{MMb} \\ \textsf{join} (\textsf{Mfx}) &: \textsf{Mb} \end{align}
Abstracting over \(\textsf f\), \[\lambda f.\textsf{join} (\textsf{Mfx}) : (\textsf a \to \textsf{Mb}) \to \textsf{Mb}\] and then over \(\textsf x\), \[\lambda \textsf x. \lambda \textsf f.\textsf{join} (\textsf{Mfx}) : \textsf{Ma} \to (\textsf a \to \textsf{Mb}) \to \textsf{Mb}\] Hence, \[\texttt{>>=} := \lambda \textsf x. \lambda \textsf f.\textsf{join} (\textsf{Mfx}) : \textsf{Ma} \to (\textsf a \to \textsf{Mb}) \to \textsf{Mb}.\]
Really, all we have shown is that \(\textsf{join}\) and \(\texttt{>>=}\) are derivable from each other and that they have the correct type. We haven't shown that the unit laws or associativity hold. I will leave that to the reader or a future post. Regardless, \(\textsf{join}\) corresponds to the components of \(\mu\) and since we can derive \(\texttt{>>=}\) from \(\textsf{join}\), a monad defined using \(\textsf{unit}\) and \(\texttt{>>=}\) is still a monad in the categorical sense. Moreover, it also means the programmer can specify a monad using just \(\textsf{unit}\) and \(\textsf{join}\) (and functor action on functions) if that is preferred over \(\texttt{>>=}\).
In Haskell the list monad is defined as follows.
return :: a -> [a]
return x = [x]
>>= :: [a] -> (a -> [b]) -> [b]
x >>= f = concat (map f x)
From the section above and the definition of >>=, we can see that \(\textsf{join}\) for the list monad is concat.
We can think of the list monad as a generalization of the maybe monad. Whereas Maybe considers the outputs of a function and adds on another output to represent failure, the list monad can be thought of as all potential outputs of a function.
In category theory, the list monad is the free monoid monad induced from the free-forgetful adjunction between \(\mathcal Set\) and \(\mathcal Mon\). That is, there is a endofunctor \(T: \mathcal Set \to \mathcal Set\), with \[Ta = \bigsqcup_{n\geq 0} a^n\]
The components of \(\eta\) are the inclusions \(\eta_a : a \hookrightarrow Ta\), and the components of the multiplication \(\mu\) is given by concatenation of lists.
We conclude by analyzing a monad in neither the context of category theory nor functional programming. In a terse summary, formal semantics (of natural language) is the study of the meaning of language using mathematical and logical structures. An important assumption is that meaning of a sentence is determined by its constituents; this is the principle of compositionality. In the truth-conditional tradition, following Frege, parts of sentences are defined as functions and these functions compose together to form a sentence. Contemporary techniques define the denotation of a word using a lambda abstraction and the simply typed lambda calculus \(\lambda^\to\).
The particular linguistic feature we will examine is indefinites. The rough idea is that indefinites are far more complex than first order logic has us believe. Naively, an indefinite article such as \(\text{a}\) is given an existential reading, i.e. the function⁷, \[[\![\text{a}]\!] := \lambda P. \exists x P(x): (e \to t) \to t,\] which takes as an argument, a predicate \(P\). For example, if \([\![\text{book}]\!] = B\) is the predicate of being a book then the denotation of \(\text{a book}\) would compute as \begin{align} [\![\text{a book}]\!] &= [\![\text{a}]\!] \space [\![\text{book}]\!] \\ &= \lambda P. \exists x P(x) \space [\![\text{book}]\!] \\ &= \lambda P. \exists x P(x) \space B \\ &=\exists x B(x). \end{align}
The problem is that an existential reading of an indefinite rarely matches empirical data. Charlow (2020), claims that indefinites denote sets of alternatives, this has type \(Se\) as opposed to \(e\). In fact \(S\) is type constructor which takes a type \(a\) and creates the type of sets containing elements with type \(a\). The type constructor \(S\) has the structure of a monad; it's unit and bind operators are defined below, \begin{align} &\eta : a \to Sa \\ &\eta := \lambda x.\{x\} \\ \\ &\texttt{>>=}\space: Sa \to (a \to Sb) \to Sb \\ &\texttt{>>=}\space := \lambda m.f. \bigcup_{x\in m} f\space x. \end{align}
As an example, let's work through: \(\text{John read a book}\). We will denote \([\![\text{John}]\!]\) as \(j\), and \([\![\text{read}]\!]\) as a type \(e \to e \to t\) function (it's precise denotation is not important for seeing the monadic structure). However, \([\![\text{book}]\!]\) is now defined as the set of all individuals such that \(B\), i.e., \(\{z \space|\space B(z)\} : Se\). Let's start with \(j \space \text{read} \space y\), for an arbitrary \(y : e\). \[[\![\text{read}]\!] \space y \space j : t\] For this to interact nicely with our other operators we need to bump it up into the enriched type space using \(\eta\), \begin{align} \eta([\![\text{read}]\!] \space y \space j) &: St \\ \{[\![\text{read}]\!] \space y \space j\} &: St. \end{align} We can abstract over \(y\) to obtain the function \[\lambda y. \{[\![\text{read}]\!] \space y \space j\} : e \to St.\] Now see what happens when we use \(\texttt{>>=}\), \begin{align} \{z \space|\space B(z)\} &: Se \\ \{z \space|\space B(z)\} \space\texttt{>>=}\space &: (e \to St) \to St \\ \{z \space|\space B(z)\} \space\texttt{>>=}\space \lambda y. \{[\![\text{read}]\!] \space y \space j\} &: St \\ \end{align} This last expression is precisely the type we want; simplifying, \begin{align} \{z \space|\space B(z)\} \space\texttt{>>=}\space \lambda y. \{[\![\text{read}]\!] \space y \space j\} &= \bigcup_{x\in \{z \space|\space B(z)\}} \lambda y. \{[\![\text{read}]\!] \space y \space j\} \space x \\ &= \bigcup_{x\in \{z \space|\space B(z)\}} \{[\![\text{read}]\!] \space x \space j\} \\ &= \{[\![\text{read}]\!] \space x \space j \space |\space B(x)\}. \end{align} This yields the set of all denotations of \[j \space \text{read} \space x \space \text{such that} \space x \space \text{is a book},\] or more succinctly: \(\text{John read a book}\).
[1] There is a bit more going on here. Behind the scenes we require that \(\mathcal C\) is a monoidal category, this gives us a bifunctor \(\otimes : M \times M \to M\) and a unit object \(I\). Furthermore, we have morphisms \(\alpha: M \otimes (M \otimes M) \to (M \otimes M) \otimes M\) and \(\lambda : I \otimes M \to M\) and \(\rho : M \otimes I \to M\) called the associator, left unitor, and right unitor respectively. It is beyond the scope of this post to delve into monoidal categories. We take \(\alpha\) and \(\lambda, \rho\) to all be the identity, in which case the structure we get is called a strict monoidal category. This allows us not to worry about higher coherence conditions; it also allows us to drop parentheses.↩︎
[2] Technically, we require the domain category \(\mathcal C\) to be small. A category is small if it has only a sets worth of objects and morphisms.↩︎
[3] Note that we can choose either \(\to\) or \(\Rightarrow\) to represent our morphisms in a functor category; both notations are common.↩︎
[4] Surprisingly, the converse is true as well: every monad comes from a pair of adjoint functors, although it is not unique. There are two constructions for a monad \((T,\eta, \mu)\). The Kleisli category \(\mathcal C _{T}\) and the Eilenberg-Moore category \(\mathcal C ^{T}\).↩︎
[5] The function unit, whose name reflects the category theoretic definition of \(\eta: 1 \Rightarrow T\), is sometimes also called return.↩︎
[6] In Haskell, action on morphisms is done using the function fmap :: (a -> b) -> f a -> f b.↩︎
[7] The types \(e\) and \(t\) are the types of individuals and truth values respectively.↩︎