Monads and Algebras/The Kleisli Category and Monads in Programming

Lesson 7.31,355 words

The Kleisli Category and Monads in Programming

The Kleisli category of a monad has the same objects as the base but takes arrows A to TB, composed by mapping and flattening. These arrows are effectful programs, Kleisli composition is the bind of functional programming, and the Kleisli adjunction is the initial resolution of the monad, with Eilenberg–Moore at the terminal end.

╌╌╌╌

The Eilenberg–Moore category resolves a monad into an adjunction by building the category of all its algebras. Kleisli's construction, a decade older, resolves the same monad with far less structure: keep the objects of the base category, and redefine what an arrow is.1 The resulting category is the category of free algebras. Read through computer science, it is the category of effectful programs, with the monad's multiplication as the sequencing operation.

The construction

To follow with : run , landing in ; the next step expects a bare , so apply to it, giving ; the result is doubly wrapped, so flatten with . Each piece of the monad has a role. lifts the second program over the first one's effect, merges the two layers of effect, and provides the do-nothing program.

Kleisli composition of and : lift through , then flatten the double layer with the multiplication ; the long arrow is the Kleisli composite .

The verification uses each monad law once. Associativity of follows from the associativity law of the monad plus naturality of ; the unit laws of the monad make a two-sided identity.2

The Kleisli adjunction

resolves the monad. Define

  • by and, for , (a pure program, run through the unit);
  • by and, for a Kleisli arrow , .

Then , and with the induced multiplication equal to .3 The monad we started from is recovered, so every monad arises from an adjunction by this construction alone — the Eilenberg–Moore route is a second, independent proof of the same fact.

Kleisli arrows as effectful programs

Barr & Wells model a functional programming language as a category: types are objects, programs are arrows, and composition is running one program after another.4 That model handles pure programs. A program with an effect — one that may fail, log output, consult state, or return several results — does not fit the shape ; it fits for the monad encoding the effect. The Kleisli category is then the category whose arrows are effectful programs, and Kleisli composition runs them in sequence.

MonadKleisli arrow Sequencing behavior of
maybe, partial program, may failfailure anywhere aborts the chain
list, nondeterministic programrun the next step on every result, concatenate
writer, program with a log in a monoid combine logs with the monoid operation
reader, program reading an environment pass the same environment to both steps
state, program threading state feed the updated state to the next step
Kleisli composition on the list monad at : apply to each letter of (the map step ), then concatenate the resulting lists (the flatten step ). The empty list from contributes nothing.

For the maybe monad, take partial programs and . Then sends the failure point to the outer failure point, and merges the two failure points into one. The composite fails when either stage fails and returns otherwise, the propagation a programmer would otherwise write by hand as a case analysis.

The same element-chase works for the state monad. Take and Kleisli arrows and : each is a program that, given a start state, returns a result and an end state. Starting from and :

  • : the first program runs, producing and an updated state ;
  • is the function -shaped element of — a stateful computation returning another stateful computation;
  • runs the outer computation and feeds its end state to the inner one, giving .

The composite threads the state from left to right; the multiplication carries the state-passing. Sequential, stateful execution order is part of for this particular , not a convention added to the notation.

Bind

Functional languages present Kleisli composition through the operator bind, written >>=. Bind takes an effectful value and a Kleisli arrow and applies the arrow under the effect:

Bind and Kleisli composition are interdefinable: , and conversely bind is composition with a constant first program. In this notation the monad laws become the three program equivalences

which say that pure steps can be inlined and that sequencing is associative — a block of effectful code means the same thing however it is parenthesized. do-notation is the direct syntax for iterated bind: each line binds the result of a Kleisli arrow and passes it on, and the desugaring is a right-nested chain of >>=. The associativity law is what makes the flat, line-by-line reading legitimate.

Bind glues an effectful value in to a program : map under the effect, then flatten. A do-block is a chain of these gluings.

Substitution and evaluation

Barr & Wells give a reading of Kleisli arrows that predates the effects vocabulary: substitution.5 Take the list monad and a Kleisli arrow on alphabets , with and . Applying to the string substitutes a string for each letter:

and concatenates the result to . The multiplication carries out a computation: it evaluates a formal expression using the algebra structure — here the monoid operation, since the algebras of the list monad are monoids. For a monad built from ring-like structure the free algebra consists of polynomial expressions and evaluates the polynomial. Kleisli arrows are substitutions; is evaluation. This viewpoint, developed through the notion of strong monad, is the root of the monads-as-computation literature.6

The Kleisli category as free algebras

The two resolutions of a monad are related concretely: the Kleisli category is the full subcategory of the Eilenberg–Moore category on the free algebras.

The equivalence sends the Kleisli object to the free algebra on ; a Kleisli arrow corresponds, by freeness, to a unique algebra morphism . Under this identification becomes the restriction of the Eilenberg–Moore forgetful functor.

The resolution spectrum

Fix a monad on and consider all adjunctions inducing it. These form a category (arrows are functors between the codomains commuting with both sides), and the two constructions of this module are its endpoints:

  • Kleisli is initial. For any inducing adjunction with codomain there is a unique functor commuting with the adjunctions — it sends to , and exists because every Kleisli object is free.
  • Eilenberg–Moore is terminal. The comparison functor is the unique functor the other way.
Every adjunction resolving the monad sits between the Kleisli category (initial: free algebras only) and the Eilenberg–Moore category (terminal: all algebras); each double edge to the base (drawn ) is an adjunction inducing the same monad.

Any category of things the monad acts on therefore contains the free algebras and embeds in the full category of algebras. For the list monad the spectrum runs from the category of free monoids to the category of all monoids, with every variety of monoid-like structure inducing the same monad falling in between.

Two factorizations, two disciplines

The contrast between the endpoints organizes how the two fields use monads.

KleisliEilenberg–Moore
objectsthose of all -algebras
arrowsstructure-preserving maps
position among resolutionsinitialterminal
algebras representedfree ones onlyall
natural readingprograms, substitutionsalgebraic structures
home disciplinecomputer sciencemathematics

Mathematics centers on the whole category of algebras (monadicity, transfer of limits, algebraic theories), so Eilenberg–Moore dominates. Computer science centers on sequencing effectful computations over base types, which never leaves the free algebras, so Kleisli dominates.8 Both categories induce the monad exactly.

Dropping the unit and multiplication and keeping only the endofunctor gives the theory of algebras for an endofunctor, where initiality replaces freeness and inductive datatypes appear as least fixed points.

Footnotes

  1. Barr & Wells, Category Theory for Computing Science, §14.4.1 — the Kleisli category : same objects, arrows , composite , identity ; "due to Kleisli 1965, has proven to be quite useful in theoretical computer science."
  2. Barr & Wells, §14.4.5 Exercises 1–2 — is the Kleisli identity and Kleisli composition is associative.
  3. Barr & Wells, §14.4.1 — the functors , and , with and .
  4. Barr & Wells, §2.2.4 — a functional programming language has a category structure: types as objects, operations as arrows, composition as the composition constructor.
  5. Barr & Wells, §14.4.4 — the list-triple example , : substitutes and concatenates, it is instructive in this situation to think of as carrying out a computation.
  6. Barr & Wells, §14.4.4 — the strong-monad development of monads-as-computation, citing Kock, Moggi, Wadler, and others.
  7. Barr & Wells, §14.4.4 — The Kleisli category of a triple is equivalent to the full subcategory of free -algebras.
  8. Barr & Wells, §14.4.2 — the Eilenberg–Moore construction has been the more interesting one in mathematics, the Kleisli construction in computer science.

╌╌ END ╌╌