Previous posts have focussed quite a lot on general theory. In this post, we are going to examine a couple of specific monads in a fair amount of detail. Both can be seen as dealing with computations parameterised by a notion of external state.

## The Reader or Environment Monad

For any set , there is a monad with:

**Endofunctor**: The monad endofunctor is .**Unit**: The unit at maps its input to the constant function .**Multiplication**: The multiplication acts as follows .

This monad is called the **reader** or **environment monad**. The computational interpretation of this monad is that a function produces an output that depends on some state or environment it can read. Note the environment is fixed, computations cannot make modifications to it – this will be addressed later.

**Aside:** This monad arises via an adjunction involving slice categories. There is an obvious forgetful functor . This has a right adjoint , with action on objects . In turn, this functor has a further right adjoint . The composite induces the reader monad.

At this level of abstraction, it is not immediately obvious that this adjunction induces the right monad. To at least convince ourselves that the endofunctors agree, we note there is then a series of bijections between hom sets:

We then note that , and via Cartesian closure functions bijectively correspond to functions . Therefore, . (The abstract argument generalises well beyond ).

Our main interest is to consider the reader monad from an algebraic perspective. To keep things as simple as possible, we are going to choose . So computations have access to a single binary bit of external data, which can be set low (0) or high (1). As usual, we would like to have an algebraic presentation of this monad. It is natural to introduce a binary **lookup** operation , such that informally we interpret

as a computation which lookups up what to do depending on the environment value, continuing as if the bit is low, or if it is high. We now need to identify some suitable equational axioms that this operation should respect. An immediate idea is to require the operation to be idempotent, that is

Intuitively, if we do regardless of whether the environment bit is high or low, that is the same as behaving exactly as . A second axiom that springs to mind is:

Here the idea is that:

- If the bit is low, we will act as the left component of the left component.
- If the bit is high, we will act as the right component of the right component.

In fact, it will turn out that these two axioms are exactly what we need. A simple consequence of the axioms is that:

So the operation is associative. So we can now avoid the annoyance of writing brackets everywhere. We also notice that:

From the above equations, if we see a sequence of operations, we can eliminate everything but the end points. Combining this with idempotence, it is hopefully not two hard to convince yourself that every term is equal to a unique term of the form . So the equivalence classes of terms over can be identified with pairs of elements from , equivalently elements of .

Finally, we note that

In fact, the following are equivalent for a structure over a binary operator :

- The equations and hold.
- The equations and hold.

For the bottom to top direction, using associativity to ignore brackets:

Using this ability to insert arbitrary elements twice, we calculate:

Finally, to show idempotence, reusing the first equation we proved:

The first set of equations we derived from computational intuitions, the second set of equations identify these structures as naturally occurring algebraic objects known as **rectangular bands**. (A band is an associative idempotent binary operation.) So the Eilenberg-Moore category of the reader monad on a bit is the category of rectangular bands and their homomorphisms.

## The State Monad

We have already encountered the state monad, as the monad induced by the Cartesian closed structure on . More precisely, we should refer to this as the **global state monad**.

Explicitly, for a fixed set of states , this monad has:

**Endofunctor**: .**Unit**: .**Multiplication**: .

Again, we are going to keep things as simple as possible, and consider a one bit state space, so . We would like to find an equational presentation for this monad. An obvious place to start is to extend the presentation for the one bit reader monad above, which gives us the infrastructure to decide how to proceed based on the current state. A natural next step is to add operations to manipulate the bit. We could add two unary **update** operations, say with and meaning set the state high (low) and proceed as . We can actually make do with a single **bit flip** operation, which we shall denote with the intuitive reading of flip the state to its opposite value, and proceed as . We quickly note that we can define:

So the explicit bit setting operations are definable by only flipping the bit if it is the wrong value. Obviously, we expect that

as flipping the bit twice should leave us back where we started. We also expect flipping a bit to reverse how computation proceeds:

In fact, these equations give a presentation of the one bit state monad. Using the chosen equations, every term is equal to one of the form

where both and are either a variable, or of the form . This encodes a function taking a bit, saying left or right, and return a variable, and applying a flip to the state if appropriate. That is, an element of .

## Generalising

To be more realistic, we really should consider larger state spaces or environments. Algebraically, this means instead of a binary lookup operation specifying which of two choices to take depending on a bit value, for an environment with possible values, we require an -ary operation. As infix notation is no longer appropriate, we shall write lookup as:

The two axioms that induce the reader monad are the obvious extensions of those for a binary bit.

You may be wondering what to do if the environment is infinite in size. There are well-defined generalisations of universal algebra where operations of these bigger arities are permitted. As long as the maximum size of the operations is bounded, this all pretty much works as in the finite case, so we shall stick with that to keep the notation clearer.

For the state monad, we also need to think about how to change the state. Generalising the bit flip operation seems unnatural, for example should we rotate through the states in some arbitrary order? A better choice is to make the update operations primitive. Without loss of generality, it is notationally convenient to fix a state space of natural numbers. We introduce a unary operation for each . The intuitive reading is that updates the state to and continues as . The equations we require, with their intuitive readings are:

- . If we don’t depend on the state, we can ignore it.
- . If the state isn’t modified, we keep making the same choices.
- . A second state change overwrites the first.
- . Update decides a subsequent lookup.

You may have expected the first axiom to be

In fact, this equation is derivable using the first two. The binary case is:

The general calculation is just notationally a bit harder to read.

The equations above appear in “Notions of Computation Determine Monads” by Plotkin and Power. In fact, they consider a further generalisation, reflecting a more realistic computational setting. We now consider a situation in which we have a set of memory addresses , and each state has its own independent state value.

If we assume each memory location can take possible values, we require an -ary lookup operation for each , and update operations , intuitively setting address to value . We require the previous equations for each address:

- . If we don’t depend on the state at an address, we can ignore it.
- . If the state at an address isn’t modified, we keep making the same choices when looking up at that address.
- . A second state change at the same address overwrites the first.
- . Update decides a subsequent lookup at the same address.

We also require some additional axioms, which encode that the states at different addresses don’t interfere with each other.

- where . Choices based on different addresses commute with each other.
- where . Consecutive updates at different addresses commute with each other.
- where . Updates and lookups at different addresses commute with each other.

The resulting monad is the state monad on . Although the algebraic perspective on the reader and state monads was somewhat involved, this does pay off. For example, we now have the data needed to introduce algebraic operations and effect handlers for these monads.

As usual, there are lots more details to take care of in realistic work, such as moving beyond the category , but the underlying intuitions transfer well. Interested readers should read the Plotkin and Power paper mentioned above, which also covers more advanced topics, such as a monad for local state.

## One thought on “Monad bits and pieces”