The idea goes back to the adjunction between extension and intension in set theory—you can define a set by its *extension*, that is by listing its elements:

or by its *intension*, that is by characterizing those elements:

Expressions in the latter form are called *set comprehensions*. They inspired a programming notation in the SETL language from NYU, and have become widely known through list comprehensions in languages like Haskell. The structure needed of sets or of lists to make this work is roughly that of a *monad*, and Phil Wadler showed how to generalize comprehensions to arbitrary monads, which led to the “**do**” notation in Haskell. Around the same time, Phil Trinder showed that comprehensions make a convenient database query language. The comprehension notation has been extended to cover other important aspects of database queries, particularly aggregation and grouping. Monads and aggregations have very nice algebraic structure, which leads to a useful body of laws to support database query optimization.

Just as a warm-up, here is a reminder about Haskell’s list comprehensions.

This (rather concocted) example yields the list of all values of the expression as is drawn from and from and such that is divisible by , namely .

To the left of the vertical bar is the *term* (an expression). To the right is a comma-separated sequence of *qualifiers*, each of which is either a *generator* (of the form , with a variable and a list expression ) or a *filter* (a boolean expression). The scope of a variable introduced by a generator extends to all subsequent generators and to the term. Note that, in contrast to the mathematical inspiration, bound variables need to be generated from some existing list.

The semantics of list comprehensions is defined by translation; see for example Phil Wadler’s Chapter 7 of The Implementation of Functional Programming Languages. It can be expressed equationally as follows:

(Here, denotes the empty sequence of qualifiers. It’s not allowed in Haskell, but it is helpful in simplifying the translation.)

Applying this translation to the example at the start of the section gives

More generally, a generator may match against a pattern rather than just a variable. In that case, it may bind multiple (or indeed no) variables at once; moreover, the match may fail, in which case it is discarded. This is handled by modifying the translation for generators to use a function defined by pattern-matching, rather than a straight lambda-abstraction:

or, more perspicuously,

It is clear from the above translation that the necessary ingredients for list comprehensions are , singletons, , and the empty list. The first three are the operations arising from lists as a functor and a monad, which suggests that the same translation might be applicable to other monads too. But the fourth ingredient, the empty list, does not come from the functor and monad structures; that requires an extra assumption:

Then the translation for list comprehensions can be generalized to other monads:

(so ). The actual monad to be used is implicit; if we want to be explicit, we could use a subscript, as in ““.

This translation is different from the one used in the Haskell language specification, which to my mind is a little awkward: the empty list crops up in two different ways in the translation of list comprehensions—for filters, and for generators with patterns—and these are generalized in two different ways to other monads (to the method of the class in the first case, and the method of the class in the second). I think it is neater to have a monad subclass with a single method subsuming both these operators. Of course, this does mean that the translation forces a monad comprehension with filters or possibly failing generators to be interpreted in a monad in the subclass rather than just —the type class constraints that are generated depend on the features used in the comprehension. (Perhaps this translation was tried in earlier versions of the language specification, and found wanting?)

Taking this approach gives basically the monad comprehension notation from Wadler’s Comprehending Monads paper; it loosely corresponds to Haskell’s **do** notation, except that the term is to the left of a vertical bar rather than at the end, and that filters are just boolean expressions rather than introduced using .

We might impose the law that is a “left” zero of composition, in the sense

or, in terms of comprehensions,

Informally, this means that any failing steps of the computation cleanly cut off subsequent branches. Conversely, we do not require that is a “right” zero too:

This would have the consequence that a failing step also cleanly erases any effects from earlier parts of the computation, which is too strong a requirement for many monads—particularly those of the “launch missiles now” variety. (The names “left-” and “right zero” make more sense when the equations are expressed in terms of the usual Haskell bind operator , which is a kind of sequential composition.)

One more ingredient is needed in order to characterize monads that correspond to “collection classes” such as sets and lists, and that is an analogue of set union or list append. It’s not difficult to see that this is inexpressible in terms of the operations introduced so far: given only collections of at most one element, any comprehension using generators of the form will only yield another such collection, whereas the union of two one-element collections will in general have two elements.

To allow any finite collection to be expressed, it suffices to introduce a binary union operator :

We require composition to distribute over union, in the following sense:

or, in terms of comprehensions,

For the remainder of this post, we will assume a monad in both and . Moreover, we will assume that is the unit of , and is both a left- and a right zero of composition. To stress the additional constraints, we will write “” for “” from now on. The intention is that such monads exactly capture collection classes; Phil Wadler has called these structures *ringads*. (He seems to have done so in an unpublished note *Notes on Monads and Ringads* from 1990, which is cited by some papers from the early 1990s. But Phil no longer has a copy of this note, and it’s not online anywhere… I’d love to see a copy, if anyone has one!)

(There are no additional methods; the class is the intersection of the two parent classes and , with the union of the two interfaces, together with the laws above.) I used roughly the same construction already in the post on Horner’s Rule.

As well as (finite) sets and lists, ringad instances include (finite) bags and a funny kind of binary tree (externally labelled, possibly empty, in which the empty tree is a unit of the binary tree constructor). These are all members of the so-called Boom Hierarchy of types—a name coined by Richard Bird, for an idea due to Hendrik Boom, who by happy coincidence is named for one of these structures in his native language. All members of the Boom Hierarchy are generated from the empty, singleton, and union operators, the difference being whether union is associative, commutative, and idempotent. Another ringad instance, but not a member of the Boom Hierarchy, is the type of probability distributions—either normalized, with a weight-indexed family of union operators, or unnormalized, with an additional scaling operator.

The well-behaved operations over monadic values are called the *algebras* for that monad—functions such that and . In particular, is itself a monad algebra. When the monad is also a ringad, necessarily distributes also over —there is a binary operator such that (exercise!). Without loss of generality, we write for ; these are the “reductions” of the Bird–Meertens Formalism. In that case, is a ringad algebra.

The algebras for a ringad amount to aggregation functions for a collection: the sum of a bag of integers, the maximum of a set of naturals, and so on. We could extend the comprehension notation to encompass aggregations too, for example by adding an optional annotation, writing say ““; although this doesn’t add much, because we could just have written “” instead. We could generalize from reductions to collection homomorphisms ; but this doesn’t add much either, because the map is easily combined with the comprehension—it’s easy to show the “map over comprehension” property

Leonidas Fegaras and David Maier develop a monoid comprehension calculus around such aggregations; but I think their name is inappropriate, because nothing forces the binary aggregating operator to be associative.

Note that, for to be well-defined, must satisfy all the laws that does— must be associative if is associative, and so on. It is not hard to show, for instance, that there is no on sets of numbers for which ; such an would have to be idempotent, which is inconsistent with its relationship with . (So, although denotes the sum of the squares of the odd elements of bag , the expression (with now a set) is not defined, because is not idempotent.) In particular, must be the unit of , which we write .

We can derive translation rules for aggregations from the definition

For empty aggregations, we have:

For filters, we have:

For generators, we have:

And for sequences of qualifiers, we have:

Putting all this together, we have:

We have seen that comprehensions can be interpreted in an arbitrary ringad; for example, denotes (the set of) the squares of the odd elements of (the set) , whereas denotes the bag of such elements, with a bag. Can we make sense of “heterogeneous comprehensions”, involving several different ringads?

Let’s introduced the notion of a *ringad morphism*, extending the familiar analogue on monads. For monads and , a monad morphism is a natural transformation —that is, a family of arrows, coherent in the sense that for —that also preserves the monad structure:

A ringad morphism for ringads is a monad morphism that also respects the ringad structure:

Then a ringad morphism behaves nicely with respect to ringad comprehensions—a comprehension interpreted in ringad , using existing collections of type , with the result transformed via a ringad morphism to ringad , is equivalent to the comprehension interpreted in ringad in the first place, but with the initial collections transformed to type . Informally, there will be no surprises arising from when ringad coercions take place, because the results are the same whenever this happens. This property is straightforward to show by induction over the structure of the comprehension. For the empty comprehension, we have:

For filters, we have:

For generators:

And for sequences of qualifiers:

For example, if is the obvious ringad morphism from bags to sets, discarding information about the multiplicity of repeated elements, and a bag of numbers, then

and both yield the set of squares of the odd members of . As a notational convenience, we might elide use of the ringad morphism when it is “obvious from context”—we might write just even when is a bag, relying on the “obvious” morphism . This would allow us to write, for example,

(writing for the extension of a bag), instead of the more pedantic

There is a forgetful function from any poorer member of the Boom hierarchy to a richer one, flattening some distinctions by imposing additional laws—for example, from bags to sets, flattening distinctions concerning multiplicity—and I would class these forgetful functions as “obvious” morphisms. On the other hand, any morphisms in the opposite direction—such as sorting, from bags to lists, and one-of-each, from sets to bags—are not “obvious”, and so should not be elided; and similarly, I’m not sure that I could justify as “obvious” any morphisms involving non-members of the Boom Hierarchy, such as probability distributions.

]]>

*Accumulations* or *scans* distribute information contained in a data structure across that data structure in a given direction. The paradigmatic example is computing the running totals of a list of numbers, which can be thought of as distributing the numbers rightwards across the list, summing them as you go. In Haskell, this is an instance of the operator:

A special case of this pattern is to distribute the elements of a list rightwards across the list, simply collecting them as you go, rather than summing them. That’s the function, and it too is an instance of :

It’s particularly special, in the sense that it is the most basic ; any other instance can be expressed in terms of it:

This is called the *Scan Lemma* for . Roughly speaking, it states that a replaces every node of a list with a applied to that node’s predecessors. Read from right to left, the scan lemma is an efficiency-improving transformation, eliminating duplicate computations; but note that this only works on expressions where is a , because only then are there duplicate computations to eliminate. It’s an important result, because it relates a clear and simple specification on the right to a more efficient implementation on the left.

However, the left-to-right operators , , and are a little awkward in Haskell, because they go against the grain of the cons-based (ie, right-to-left) structure of lists. I leave as a simple exercise for the reader the task of writing the more natural , , and , and identifying the relationships between them. Conversely, one can view etc as the natural operators for snoc-based lists, which are constructed from nil and snoc rather than from nil and cons.

What would , , , etc look like on different—and in particular, non-linear—datatypes? Let’s consider a simple instance, for homogeneous binary trees; that is, trees with a label at both internal and external nodes.

for which the obvious fold operator is

I’m taking the view that the appropriate generalization is to distribute data “upwards” and “downwards” through such a tree—from the leaves towards the root, and vice versa. This does indeed specialize to the definitions we had on lists when you view them vertically in terms of their “cons” structure: they’re long thin trees, in which every parent has exactly one child. (An alternative view would be to look at distributing data horizontally through a tree, from left to right and vice versa. Perhaps I’ll come back to that another time.)

The upwards direction is the easier one to deal with. An upwards accumulation labels every node of the tree with some function of its *descendants*; moreover, the descendants of a node themselves form a tree, so can be easily represented, and folded. So we can quite straightforwardly define:

where yields the root of a tree:

As with lists, the most basic upwards scan uses the constructors themselves as arguments:

and any other scan can be expressed, albeit less efficiently, in terms of this:

The downwards direction is more difficult, though. A downwards accumulation should label every node with some function of its *ancestors*; but these do not form another tree. For example, in the homogeneous binary tree

the ancestors of the node labelled are the nodes labelled . One could represent those ancestors simply as a list, ; but that rules out the possibility of a downwards accumulation treating left children differently from right children, which is essential in a number of algorithms (such as the parallel prefix and tree drawing algorithms in my thesis). A more faithful rendering is to define a new datatype of *paths* that captures the left and right turns—a kind of non-empty cons list, but with both a “left cons” and a “right cons” constructor:

(I called them “threads” in my thesis.) Then we can capture the data structure representing the ancestors of the node labelled

by the expression . I leave it as an exercise for the more energetic reader to work out a definition for

to compute the tree giving the ancestors of every node, and for a corresponding .

Having seen ad-hoc constructions for a particular kind of binary tree, we should consider what the datatype-generic construction looks like. I discussed datatype-generic upwards accumulations already, in the post on Horner’s Rule; the construction was given in the paper Generic functional programming with types and relations by Richard Bird, Oege de Moor and Paul Hoogendijk. As with homogeneous binary trees, it’s still the case that the generic version of labels every node of a data structure of type with the descendants of that node, and still the case that the descendants form a data structure also of type . However, in general, the datatype does not allow for a label at every node, so we need the *labelled variant* where . Then we can define

where returns the root label of a labelled data structure—by construction, every labelled data structure has a root label—and is the unique arrow to the unit type. Moreover, we get a datatype-generic operator, and a Scan Lemma:

The best part of a decade after my thesis work, inspired by the paper by Richard Bird & co, I set out to try to define datatype-generic versions of downward accumulations too. I wrote a paper about it for MPC 1998, and then came up with a new construction for the journal version of that paper in SCP in 2000. I now think these constructions are rather clunky, and I have a better one; if you don’t care to explore the culs-de-sac, skip this section and the next and go straight to the section on derivatives.

The MPC construction was based around a datatype-generic version of the datatype above, to represent the “ancestors” of a node in an inductive datatype. The tricky bit is that data structures in general are non-linear—a node may have many children—whereas paths are linear—every node has exactly one child, except the last which has none; how can we define a “linear version” of ? Technically, we might say that a functor is linear (actually, “affine” would be a better word) if it distributes over sum.

The construction in the paper assumed that was a sum of products of literals

where each is either , , or some constant type such as or . For example, for leaf-labelled binary trees

the shape functor is , so (there are two variants), (the first variant has a single literal, ) and (the second variant has two literals, and ), and:

Then for each we define a -ary functor , where is the “degree of branching” of variant (ie, the number of s occurring in , which is the number of for which ), in such a way that

and is linear in each argument except perhaps the first. It’s a bit messy explicitly to give a construction for , but roughly speaking,

where is “the next unused ” when , and just otherwise. For example, for leaf-labelled binary trees, we have:

Having defined the linear variant of , we can construct the datatype of paths, as the inductive datatype of shape where

That is, paths are a kind of non-empty cons list. The path ends at some node of the original data structure; so the last element of the path is of type , which records the “local content” of a node (its shape and labels, but without any of its children). Every other element of the path consists of the local content of a node together with an indication of which direction to go next; this amounts to the choice of a variant , followed by the choice of one of identical copies of the local contents of variant , where is the degree of branching of variant . We model this as a base constructor and a family of “cons” constructors for and .

For example, for leaf-labelled binary trees, the “local content” for the last element of the path is either a single label (for tips) or void (for bins), and for the other path elements, there are zero copies of the local content for a tip (because a tip has zero children), and two copies of the void local information for bins (because a bin has two children). Therefore, the path datatype for such trees is

which is isomorphic to the definition that you might have written yourself:

For homogeneous binary trees, the construction gives

which is almost the ad-hoc definition we had two sections ago, except that it distinguishes singleton paths that terminate at an external node from those that terminate at an internal one.

Now, analogous to the function which labels every node with its descendants, we can define a function to label every node with its ancestors, in the form of the path to that node. One definition is as a fold; informally, at each stage we construct a singleton path to the root, and map the appropriate “cons” over the paths to each node in each of the children (see the paper for a concrete definition). This is inefficient, because of the repeated maps; it’s analogous to defining by

A second definition is as an unfold, maintaining as an accumulating parameter of type the “path so far”; this avoids the maps, but it is still quadratic because there are no common subexpressions among the various paths. (This is analogous to an accumulating-parameter definition of :

Even with an accumulating “Hughes list” parameter, it still takes quadratic time.)

The downwards accumulation itself is defined as a path fold mapped over the paths, giving a Scan Lemma for downwards accumulations. With either the fold or the unfold definition of paths, this is still quadratic, again because of the lack of common subexpressions in a result of quadratic size. However, in some circumstances the path fold can be reassociated (analogous to turning a into a ), leading finally to a linear-time computation; see the paper for the details of how.

I was dissatisfied with the “…”s in the MPC construction of datatype-generic paths, but couldn’t see a good way of avoiding them. So in the subsequent SCP version of the paper, I presented an alternative construction of downwards accumulations, which does not go via a definition of paths; instead, it goes directly to the accumulation itself.

As with the efficient version of the MPC construction, it is coinductive, and uses an accumulating parameter to carry in to each node the seed from higher up in the tree; so the downwards accumulation is of type . It is defined as an unfold, with a body of type

The result of applying the body will be constructed from two components, of types and : the first gives the root label of the accumulation and the seeds for processing the children, and the second gives the children themselves.

These two components get combined to make the whole result via a function

This will be partial in general, defined only for pairs of -structures of the same shape.

The second component of is the easier to define; given input , it unpacks the to , and discards the and the (recall that is the labelled variant of , where ).

For the first component, we enforce the constraint that all output labels are dependent only on their ancestors by unpacking the and pruning off the children, giving input . We then suppose as a parameter to the accumulation a function of type to complete the construction of the first component. In order that the two components can be zipped together, we require that is shape-preserving in its second argument:

where is the unique function to the unit type. Then, although the built from these two components depends on the partial function , it will still itself be total.

The SCP construction gets rid of the “…”s in the MPC construction. It is also inherently efficient, in the sense that if the core operation takes constant time then the whole accumulation takes linear time. However, use of the partial function to define a total accumulation is a bit unsatisfactory, taking us outside the domain of sets and total functions. Moreover, there’s now only half an explanation in terms of paths: accumulations in which the label attached to each node depends only on the *list* of its ancestors, and not on the left-to-right ordering of siblings, can be factored into a list function (in fact, a ) mapped over the “paths”, which is now a tree of lists; but accumulations in which left children are treated differently from right children, such as the parallel prefix and tree drawing algorithms mentioned earlier, can not.

After another interlude of about a decade, and with the benefit of new results to exploit, I had a “eureka” moment: the linearization of a shape functor is closely related to the beautiful notion of the *derivative* of a datatype, as promoted by Conor McBride. The crucial observation Conor made is that the “one-hole contexts” of a datatype—that is, for a container datatype, the datatype of data structures with precisely one element missing—can be neatly formalized using an analogue of the rules of differential calculus. The one-hole contexts are precisely what you need to identify which particular child you’re talking about out of a collection of children. (If you’re going to follow along with some coding, I recommend that you also read Conor’s paper Clowns to the left of me, jokers to the right. This gives the more general construction of *dissecting* a datatype, identifying a unique hole, but also allowing the “clowns” to the left of the hole to have a different type from the “jokers” to the right. I think the explanation of the relationship with the differential calculus is much better explained here; the original notion of derivative can be retrieved by specializing the clowns and jokers to the same type.)

The essence of the construction is the notion of a *derivative* of a functor . For our purposes, we want the derivative in the second argument only of a bifunctor; informally, is like , but with precisely one missing. Given such a one-hole context, and an element with which to plug the hole, one can reconstruct the whole structure:

That’s how to consume one-hole contexts; how can we produce them? We could envisage some kind of inverse of , which breaks an -structure into an element and a context; but this requires us to invent a language for specifying which particular element we mean— is not injective, so needs an extra argument. A simpler approach is to provide an operator that annotates every position at once with the one-hole context for that position:

One property of is that it really is an annotation—if you throw away the annotations, you get back what you started with:

A second property relates it to —each of elements in a hole position plugs into its associated one-hole context to yield the same whole structure back again:

(I believe that those two properties completely determine and .)

Incidentally, the derivative of a bifunctor can be elegantly represented as an *associated type synonym* in Haskell, in a type class of bifunctors differentiable in their second argument, along with and :

Conor’s papers show how to define instances of for all polynomial functors —anything made out of constants, projections, sums, and products.

The path to a node in a data structure is simply a list of one-hole contexts—let’s say, innermost context first, although it doesn’t make much difference—but with all the data off the path (that is, the other children) stripped away:

This is a projection of Huet’s zipper, which preserves the off-path children, and records also the subtree in focus at the end of the path:

Since the contexts are listed innermost-first in the path, closing up a zipper to reconstruct a tree is a over the path:

Now, let’s develop the function , which turns a tree into a labelled tree of paths. We will write it with an accumulating parameter, representing the “path so far”:

Given the components of a tree and a path to its root, must construct the corresponding labelled tree of paths. Since and , this amounts to constructing a value of type . For the first component of this pair we will use , the path so far. The second component can be constructed from by identifying all children via , discarding some information with judicious s, consing each one-hole context onto to make a longer path, then making recursive calls on each child:

That is,

Downwards accumulations are then path functions mapped over the result of . However, we restrict ourselves to path functions that are instances of , because only then are there common subexpressions to be shared between a parent and its children (remember that paths are innermost-first, so related nodes share a tail of their ancestors).

Moreover, it is straightforward to fuse the with , to obtain

which takes time linear in the size of the tree, assuming that and take constant time.

Finally, in the case that the function being mapped over the paths is a as well as a , then we can apply the Third Homomorphism Theorem to conclude that it is also an associative fold over lists. From this (I believe) we get a very efficient parallel algorithm for computing the accumulation, taking time logarithmic in the size of the tree—even if the tree has greater than logarithmic depth.

]]>

the essential property behind Horner’s Rule is one of distributivity. In the datatype-generic case, we will model this as follows. We are given an -algebra [for a binary shape functor ], and a -algebra [for a collection monad ]; you might think of these as “datatype-generic product” and “collection sum”, respectively. Then there are two different methods of computing a result from an structure: we can either distribute the structure over the collection(s) of s, compute the “product” of each structure, and then compute the “sum” of the resulting products; or we can “sum” each collection, then compute the “product” of the resulting structure. Distributivity of “product” over “sum” is the property that these two different methods agree, as illustrated in the following diagram.For example, with adding all the integers in an -structure, and finding the maximum of a (non-empty) collection, the diagram commutes.

There’s a bit of hand-waving above to justify the claim that this is really a kind of distributivity. What does it have to do with the common-or-garden equation

stating distributivity of one binary operator over another? That question is the subject of this post.

Recall that distributes the shape functor over the monad in its second argument; this is the form of distribution over effects that crops up in the datatype-generic Maximum Segment Sum problem. More generally, this works for any idiom ; this will be important below.

Generalizing in another direction, one might think of distributing over an idiom in both arguments of the bifunctor, via an operator , which is to say, , natural in the . This is the method of the subclass of that Bruno Oliveira and I used in our Essence of the Iterator Pattern paper; informally, it requires just that has a finite ordered sequence of “element positions”. Given , one can define .

That traversability (or equivalently, distributivity over effects) for a bifunctor is definable for any idiom, not just any monad, means that one can also conveniently define an operator for any traversable unary functor . This is because the constant functor (which takes any to ) is an idiom: the method returns the empty list, and idiomatic application appends two lists. Then one can define

where makes a singleton list. For a traversable bifunctor , we define where is the diagonal functor; that is, , natural in the . (No constant functor is a monad, except in trivial categories, so this convenient definition of contents doesn’t work monadically. Of course, one can use a writer monad, but this isn’t quite so convenient, because an additional step is needed to extract the output.)

One important axiom of that I made recent use of in a paper with Richard Bird on Effective Reasoning about Effectful Traversals is that it should be “natural in the contents”: it should leave shape unchanged, and depend on contents only up to the extent of their ordering. Say that a natural transformation between traversable functors and “preserves contents” if . Then, in the case of unary functors, the formalization of “naturality in the contents” requires to respect content-preserving :

In particular, itself preserves contents, and so we expect

to hold.

Happily, the same generic operation provides a datatype-generic means to “fold” over the elements of an -structure. Given a binary operator and an initial value , we can define an -algebra —that is, a function —by

(This is a slight specialization of the presentation of the datatype-generic MSS problem from last time; there we had . The specialization arises because we are hoping to define such an given a homogeneous binary operator . On the other hand, the introduction of the initial value is no specialization, as we needed such a value for the “product” of an empty “segment” anyway.)

Incidentally, I believe that this “generic folding” construction is exactly what is intended in Ross Paterson’s Data.Foldable library.

The other ingredient we need is an -algebra . We already decided last time to

stick toreductions—s of the form for associative binary operator ; then we also have distribution over choice: . Note also that we prohibited empty collections in , so we do not need a unit for .

On account of being an algebra for the collection monad , we also get a singleton rule .

One of the take-home messages in the *Effective Reasoning about Effectful Traversals* paper is that it helps to reduce a traversal problem for datatypes in general to a more specific one about lists, exploiting the “naturality in contents” property of traversability. We’ll use that tactic for the distributivity property in the datatype-generic version Horner’s Rule.

In this diagram, the perimeter is the commuting diagram given at the start of this post—the diagram we have to justify. Face (1) is the definition of in terms of . Faces (2) and (3) are the expansion of as generic folding of an -structure. Face (4) follows from being an -algebra, and hence being a left-inverse of . Face (5) is an instance of the naturality property of . Face (6) is the property that respects the contents-preserving transformation . Therefore, the whole diagram commutes if Face (7) does—so let’s look at Face (7)!

Here’s Face (7) again:

Demonstrating that this diagram commutes is not too difficult, because both sides turn out to be list folds.

Around the left and bottom edges, we have a fold after a map , which automatically fuses to , where is defined by

or, pointlessly,

Around the top and right edges we have the composition . If we can write as an instance of , we can then use the fusion law for

to prove that this composition equals .

In fact, there are various equivalent ways of writing as an instance of . The definition given by Conor McBride and Ross Paterson in their original paper on idioms looked like the identity function, but with added idiomness:

In the special case that the idiom is a monad, it can be written in terms of (aka ) and :

But we’ll use a third definition:

where

That is,

Now, for the base case we have

as required. For the inductive step, we have:

which completes the fusion proof, modulo the wish about distributivity for :

As for that wish about distributivity for :

which discharges the proof obligation about distributivity for cartesian product, but again modulo two symmetric wishes about distributivity for collections:

Finally, the proof obligations about distributivity for collections are easily discharged, by induction over the size of the (finite!) collection, provided that the binary operator distributes over in the familiar sense. The base case is for a singleton collection, ie in the image of (because we disallowed empty collections); this case follows from the fact that is an -algebra. The inductive step is for a collection of the form with both strictly smaller than the whole (so, if the monad is idempotent, disjoint, or at least not nested); this requires the distribution of the algebra over choice , together with the familiar distribution of over .

So, the datatype-generic distributivity for -structures of collections that we used for the Maximum Segment Sum problem reduced to distributivity for lists of collections, which reduced to the cartesian product of collections, which reduced to that for pairs. That’s a much deeper hierarchy than I was expecting; can it be streamlined?

]]>

The original problem is as follows. Given a list of numbers (say, a possibly empty list of integers), find the largest of the sums of the contiguous segments of that list. In Haskell, this specification could be written like so:

where computes the contiguous segments of a list:

and computes the sum of a list, and the maximum of a nonempty list:

This specification is executable, but takes cubic time; the problem is to do better.

We can get quite a long way just with standard properties of , , etc:

For the final step, if we can write in the form , then the of this can be fused with the to yield ; this observation is known as the *Scan Lemma*. Moreover, if takes constant time, then this gives a linear-time algorithm for .

The crucial observation is based on Horner’s Rule for evaluation of polynomials, which is the first important thing you learn in numerical computing—I was literally taught it in secondary school, in my sixth-year classes in mathematics. Here is its familiar form:

but the essence of the rule is about sums of products:

Expressed in Haskell, this is captured by the equation

(where computes the product of a list of integers).

But Horner’s Rule is not restricted to sums and products; the essential properties are that addition and multiplication are associative, that multiplication has a unit, and that multiplication distributes over addition. This the algebraic structure of a *semiring* (but without needing commutativity and a unit of addition, or that that unit is a zero of multiplication). In particular, the so-called *tropical semiring* on the integers, in which “addition” is binary and “multiplication” is integer addition, satisfies the requirements. So for the maximum segment sum problem, we get

Moreover, takes constant time, so this gives a linear-time algorithm for .

About a decade after the initial “theory of lists” work on the maximum segment sum problem, Richard Bird (with Oege de Moor and Paul Hoogendijk) came up with a datatype-generic version of the problem in the paper Generic functional programming with types and relations. It’s clear what “maximum” and “sum” mean generically, but not so clear what “segment” means for nonlinear datatypes; the point of their paper is basically to resolve that issue.

Recalling the definition of in terms of and , we see that it would suffice to develop datatype-generic notions of “initial segment” and “tail segment”. One fruitful perspective is given in Bird & co’s paper: a “tail segment” of a cons list is just a subterm of that list, and an “initial segment” is the list but with some tail (that is, some subterm) replaced with the empty structure.

So, representing a generic “tail” of a data structure is easy: it’s a data structure of the same type, and a subterm of the term denoting the original structure. A datatype-generic definition of is a little trickier, though. For lists, you can see it as follows: *every node of the original list is labelled with the subterm of the original list rooted at that node*. I find this a helpful observation, because it explains why the of a list is one element longer than the list itself: a list with elements has nodes ( conses and a nil), and each of those nodes gets labelled with one of the subterms of the list. Indeed, ought morally to take a possibly empty list and return a *non-empty list* of possibly empty lists—there are two different datatypes involved. Similarly, if one wants the “tails” of a data structure of a type in which some nodes have no labels (such as leaf-labelled trees, or indeed such as the “nil” constructor of lists), one needs a variant of the datatype providing labels at those positions. Also, for a data structure in which some nodes have multiple labels, or in which there are different types of labels, one needs a variant for which *every node has precisely one label*.

Bird & co call this the *labelled variant* of the original datatype; if the original is a polymorphic datatype for some binary shape functor , then the labelled variant is where —whatever labels may or may not have specified are ignored, and precisely one label per node is provided. Given this insight, it is straightforward to define a datatype-generic variant of the function:

where returns the root label of a labelled data structure, and is the unique arrow to the unit type. (Informally, having computed the tree of subterms for each child of a node, we make the tree of subterms for this node by assembling all the child trees with the label for this node; the label should be the whole structure rooted at this node, which can be reconstructed from the roots of the child trees.) What’s more, there’s a datatype-generic scan lemma too:

(Again, the label for each node can be constructed from the root labels of each of the child trees.) In fact, and are paramorphisms, and can also be nicely written coinductively as well as inductively. I’ll return to this in a future post.

What about a datatype-generic “initial segment”? As suggested above, that’s obtained from the original data structure by replacing some subterms with the empty structure. Here I think Bird & co sell themselves a little short, because they insist that the datatype supports empty structures, which is to say, that is of the form for some . This isn’t necessary: for an arbitrary , we can easily manufacture the appropriate datatype of “data structures in which some subterms may be replaced by empty”, by defining and .

As with , the datatype-generic version of is a bit trickier—and this time, the special case of lists is misleading. You might think that because a list has just as many initial segments as it does tail segments, so the labelled variant ought to suffice just as well here too. But this doesn’t work for non-linear data structures such as trees—in general, there are many more “initial” segments than “tail” segments (because one can make independent choices about replacing subterms with the empty structure in each child), and they don’t align themselves conveniently with the nodes of the original structure.

The approach I prefer here is just to use an unstructured collection type to hold the “initial segments”; that is, a monad. This could be the monad of finite lists, or of finite sets, or of finite bags—we will defer until later the discussion about precisely which, and write simply . We require only that it provide a -like interface, in the sense of an operator ; however, for reasons that will become clear, we will expect that it does *not* provide a operator yielding empty collections.

Now we can think of the datatype-generic version of as nondeterministically pruning a data structure by arbitrarily replacing some subterms with the empty structure; or equivalently, as generating the collection of all such prunings.

Here, supplies a new alternative for a nondeterministic computation:

and distributes the shape functor over the monad (which can be defined for all functors ). Informally, once you have computed all possible ways of pruning each of the children of a node, a pruning of the node itself is formed either as some node assembled from arbitrarily pruned children, or for the empty structure.

As we’ve seen, the essential property behind Horner’s Rule is one of distributivity. In the datatype-generic case, we will model this as follows. We are given an -algebra , and a -algebra ; you might think of these as “datatype-generic product” and “collection sum”, respectively. Then there are two different methods of computing a result from an structure: we can either distribute the structure over the collection(s) of s, compute the “product” of each structure, and then compute the “sum” of the resulting products; or we can “sum” each collection, then compute the “product” of the resulting structure. Distributivity of “product” over “sum” is the property that these two different methods agree, as illustrated in the following diagram.

For example, with adding all the integers in an -structure, and finding the maximum of a (non-empty) collection, the diagram commutes. (To match up with the rest of the story, we have presented distributivity in terms of a bifunctor , although the first parameter plays no role. We could just have well have used a unary functor, dropping the , and changing the distributor to .)

Note that is required to be an algebra for the monad . This means that it is not only an algebra for as a functor (namely, of type ), but also it should respect the extra structure of the monad: and . For the special case of monads for associative collections (such as lists, bags, and sets), and in homage to the old Squiggol papers, we will stick to *reductions*—s of the form for associative binary operator ; then we also have distribution over choice: . Note also that we prohibited empty collections in , so we do not need a unit for .

Recall that we modelled an “initial segment” of a structure of type as being of type , where . We need to generalize “product” to work on this extended structure, which is to say, we need to specify the value of the “product” of the empty structure too. Then we let , so that .

The datatype-generic version of Horner’s Rule is then about computing the “sum” of the “products” of each of the “initial segments” of a data structure:

We will use fold fusion to show that this can be computed as a single fold, given the necessary distributivity property.

(Sadly, I have to break this calculation in two to get it through WordPress’s somewhat fragile LaTeX processor… where were we? Ah, yes:)

Therefore,

(Curiously, it doesn’t seem to matter what value is chosen for .)

We’re nearly there. We start with the traversable shape bifunctor , a collection monad , and a distributive law . We are given an -algebra , an additional element , and a -algebra , such that and take constant time and distributes over in the sense above. Then

can be computed in linear time, where

and where

computes the contents of an -structure (which, like , can be defined using the traversability of ). Here’s the calculation:

The scan can be computed in linear time, because its body takes constant time; moreover, the “sum” and can also be computed in linear time (and what’s more, they can be fused into a single pass).

For example, with adding all the integers in an -structure, , and returning the greater of two integers, we get a datatype-generic version of the linear-time maximum segment sum algorithm.

As the title of their paper suggests, Bird & co carried out their development using the relational approach set out in the *Algebra of Programming* book; for example, their version of is a relation between data structures and their prunings, rather than being a function that takes a structure and returns the collection of all its prunings. There’s a well-known isomorphism between relations and set-valued functions, so their relational approach roughly looks equivalent to the monadic one I’ve taken.

I’ve known their paper well for over a decade (I made extensive use of the “labelled variant” construction in my own papers on generic downwards accumulations), but I’ve only just noticed that although they discuss the maximum segment sum problem, they don’t discuss problems based on other semirings, such as the obvious one of integers with addition and multiplication—which is, after all, the origin of Horner’s Rule. Why not? It turns out that the relational approach doesn’t work in that case!

There’s a hidden condition in the calculation, which relates back to our earlier comment about which collection monad—finite sets, finite bags, lists, etc—to use. When is the set monad, distribution over choice ()—and consequently the condition that we used in proving Horner’s Rule—require to be idempotent, because itself is idempotent; but addition is not idempotent. For the same reason, the distributivity property does not hold for addition with the set monad. But everything does work out for the bag monad, for which is not idempotent. The bag monad models a flavour of nondeterminism in which multiplicity of results matters—as it does for the sum-of-products instance of the problem, when two copies of the same segment should be treated differently from just one copy. Similarly, if the order of results matters—if, for example, we were looking for the “first” solution—then we would have to use the list monad rather than bags or sets. Seen from a monadic perspective, the relational approach is *programming with just one monad*, namely the set monad; if that monad doesn’t capture your effects faithfully, you’re stuck.

(On the other hand, there are aspects of the problem that work much better relationally. We have carefully used only for a linear order, namely the usual ordering of the integers. A partial order is more awkward monadically, because there need not be a unique maximal value. For example, it is not so easy to compute a segment with maximal sum, unless we refine the sum ordering on segments to make it once more a linear order; relationally, this works out perfectly straightforwardly. We can try the same trick of turning the relation “maximal under a partial order” into the collection-valued function “all maxima under a partial order”, but I fear that the equivalent trick on the ordering itself—turning the relation “” into the collection-valued function “all values less than this one”—runs into problems from taking us outside the world of *finite* nondeterminism.)

]]>

We know and love initial algebras, because of the ease of reasoning with their universal properties. We can tell a simple story about recursive programs, solely in terms of sets and total functions. As we discussed in the previous post, given a functor , an -algebra is a pair consisting of an object and an arrow . A *homomorphism* between -algebras and is an arrow such that :

The -algebra is *initial* iff there is a unique such for each ; for well-behaved functors , such as the polynomial functors on , an initial algebra always exists. We conventionally write “” for the initial algebra, and “” for the unique homomorphism to another -algebra . (In , initial algebras correspond to datatypes of finite recursive data structures.)

The uniqueness of the solution is captured in the universal property:

In words, is this fold iff satisfies the defining equation for the fold.

The universal property is crucial. For one thing, the homomorphism equation is a very convenient style in which to define a function; it’s the datatype-generic abstraction of the familiar pattern for defining functions on lists:

These two equations implicitly characterizing are much more comprehensible and manipulable than a single equation

explicitly giving a value for . But how do we know that this assortment of two facts about is enough to form a definition? Of course! A system of equations in this form has a *unique solution*.

Moreover, the very expression of the uniqueness of the solution as an equivalence provides many footholds for reasoning:

- Read as an implication from left to right, instantiating to to make the left-hand side trivially true, we get an
*evaluation rule*for folds: - Read as an implication from right to left, we get a proof rule for demonstrating that some complicated expression is a fold:

- In particular, we can quickly see that the identity function is a fold:

so . (In fact, this one’s an equivalence.)

- We get a very simple proof of a
*fusion rule*, for combining a following function with a fold to make another fold: - Using this, we can deduce
*Lambek’s Lemma*, that the constructors form an isomorphism. Supposing that there is a right inverse, and it is a fold, what must it look like?

So if we define , we get . We should also check the left inverse property:

And so on, and so on. Many useful functions can be written as instances of , and the universal property gives us a very powerful reasoning tool—the universal property of is a marvel to behold.

And of course, it all dualizes beautifully. An -coalgebra is a pair with . A homomorphism between -coalgebras and is a function such that :

The -coalgebra is *final* iff there is a unique homomorphism *to* it from each ; again, for well-behaved , final coalgebras always exist. We write “” for the final coalgebra, and for the unique homomorphism to it. (In , final coalgebras correspond to datatypes of finite-or-infinite recursive data structures.)

Uniqueness is captured by the universal property

which has just as many marvellous consequences. Many other useful functions are definable as instances of , and again the universal property gives a very powerful tool for reasoning with them.

There are also many interesting functions that are best described as a *combination* of a fold and an unfold. The *hylomorphism* pattern, with an unfold followed by a fold, is the best known: the unfold produces a recursive structure, which the fold consumes.

The factorial function is a simple example. The datatype of lists of natural numbers is determined by the shape functor

Then we might hope to write

where and with

More elaborately, we might hope to write as the composition of (to generate a binary search tree) and (to flatten that tree to a list), where is the shape functor for internally-labelled binary trees,

partitions a list of integers into the unit or a pivot and two sublists, and

glues together the unit or a pivot and two sorted lists into one list. In fact, any divide-and-conquer algorithm can be expressed in terms of an unfold computing a tree of subproblems top-down, followed by a fold that solves the subproblems bottom-up.

But sadly, this doesn’t work in , because the types don’t meet in the middle. The source type of the fold is (the carrier of) an initial algebra, but the target type of the unfold is a final coalgebra, and these are different constructions.

This is entirely reasonable, when you think about it. Our definitions in —the category of sets and total functions—necessarily gave us folds and unfolds as total functions; the composition of two total functions is a total function, and so a fold after an unfold ought to be a total function too. But it is easy to define total instances of that generate infinite data structures (such as a function , which generates an infinite ascending list of naturals), on which a following fold is undefined (such as “the product” of an infinite ascending list of naturals). The composition then should not be a total function.

One might try interposing a conversion function of type , coercing the final data structure produced by the unfold into an initial data structure for consumption by the fold. But there is no canonical way of doing this, because final data structures may be “bigger” (perhaps infinitely so) than initial ones. (In contrast, there is a canonical function of type . In fact, there are two obvious definitions of it, and they agree—a nice exercise!)

One might try parametrizing that conversion function with a natural number, bounding the depth to which the final data structure is traversed. Then the coercion is nicely structural (in fact, it’s a fold over the depth), and everything works out type-wise. But having to thread such “resource bounds” through the code does terrible violence to the elegant structure; it’s not very satisfactory.

The usual solution to this conundrum is to give up on , and to admit that richer domain structures than sets and total functions are required. Specifically, in order to support recursive definitions in general, and the hylomorphism in particular, one should move to the category of *continuous functions* between *complete partial orders* (CPOs). Now is not the place to give all the definitions; see any textbook on denotational semantics. The bottom line, so to speak, is that one has to accept a definedness ordering on values—both on “data” and on functions—and allow some values to be less than fully defined.

Actually, in order to give meaning to all recursive definitions, one has to further restrict the setting to *pointed* CPOs—in which there is a least-defined “bottom” element for each type , which can be given as the “meaning” (solution) of the degenerate recursive definition at type . Then there is no “empty” CPO; the smallest CPO has just a single element, namely . As with colimits in general, this smallest object is used as the start of a chain of approximations to a limiting solution. But in order for really to be an initial object, one also has to constrain the arrows to be *strict*, that is, to preserve ; only then is there a unique arrow for each . The category of *strict continuous functions* between *pointed CPOs* is called .

It so happens that in , initial algebras and final coalgebras coincide: the objects (pointed CPOs) and are identical. This is very convenient, because it means that the hylomorphism pattern works fine: the structure generated by the unfold is exactly what is expected by the fold.

Of course, it still happen that the composition yields a “partial” (less than fully defined) function; but at least it now type-checks. Categories with this initial algebra/final coalgebra coincidence are called *algebraically compact*; they were studied by Freyd, but there’s a very good survey by Adámek, Milius and Moss.

However, the story gets murkier than that. For one thing, does not have proper products. (Indeed, an algebraically compact category with products collapses.) But beyond that, —with its restriction to strict arrows—is not a good model of lazy functional programming; , with non-strict arrows too, is better. So one needs a careful balance of the two categories. The consequences for initial algebras and final coalgebras are spelled out in one of my favourite papers, Program Calculation Properties of Continuous Algebras by Fokkinga and Meijer. In a nutshell, one can only say that the defining equation for folds has a unique *strict* solution in ; without the strictness side-condition, is unconstrained (because for any ). But the situation for coalgebras remains unchanged—the defining equation for unfolds has a unique solution (and moreover, it is strict when is strict).

This works, but it means various strictness side-conditions have to be borne in mind when reasoning about folds. Done rigorously, it’s rather painful.

So, back to my confession. I want to write divide-and-conquer programs, which produce intermediate data structures and then consume them. Folds and unfolds in do not satisfy me; I want more—hylos. Morally, I realise that I should pay careful attention to those strictness side-conditions. But they’re so fiddly and boring, and my resolve is weak, so I usually just brush them aside. Is there away that I can satisfy my appetite for divide-and-conquer programs while still remaining in the pure world?

Tarmo Uustalu and colleagues have a suggestion. Final coalgebras and algebraic compactness are sufficient but not necessary for the hylo diagram above to have a unique solution; they propose to focus on *recursive coalgebras* instead. The -coalgebra is “recursive” iff, for each , there is a unique such that :

This is a generalization of initial algebras: if has an initial algebra , then by Lambek’s Lemma has an inverse , and is a recursive coalgebra. And it is a strict generalization: it also covers patterns such as *paramorphisms* (primitive recursion)—since is a recursive -coalgebra where is the functor taking to —and the “back one or two steps” pattern used in the Fibonacci function.

Crucially for us, almost by definition it covers all of the “reasonable” hylomorphisms too. For example, is a recursive -coalgebra, where is the shape functor for lists of naturals and the -coalgebra introduced above that analyzes a natural into nothing (for zero) or itself and its predecessor (for non-zero inputs). Which is to say, for each , there is a unique such that ; in particular, for the given above that returns 1 or multiplies, the unique is the factorial function. (In fact, this example is also an instance of a paramorphism.) And is a recursive -coalgebra, where is the partition function of quicksort—for any -algebra , there is a unique such that , and in particular when is the glue function for quicksort, that unique solution is quicksort itself.

This works perfectly nicely in ; there is no need to move to more complicated settings such as or , or to consider partiality, or strictness, or definedness orderings. The only snag is the need to prove that a particular coalgebra of interest is indeed recursive. Capretta et al. study a handful of “basic” recursive coalgebras and of constructions on coalgebras that preserve recursivity.

More conveniently, Taylor and Adámek et al. relate recursivity of coalgebras to the more familiar notion of *variant* function, ie well-founded ordering on arguments of recursive calls. They restrict attention to *finitary* shape functors; technically, preserving directed colimits, but informally, I think that’s equivalent to requiring that each element of has a finite number of elements—so polynomial functors are ok, as is the finite powerset functor, but not powerset in general. If I understand those sources right, for a finitary functor and an -coalgebra , the following conditions are equivalent: (i) is corecursive; (ii) is well-founded, in the sense that there is a well-founded ordering such that for each “element” of ; (iii) every element of has finite depth; and (iv) there is a coalgebra homomorphism from to .

This means that I can resort to simple and familiar arguments in terms of variant functions to justify hylo-style programs. The factorial function is fine, because ( is a finitary functor, being polynomial, and) the chain of recursive calls to which leads is well-founded; quicksort is fine, because the partitioning step is well-founded; and so on. Which takes a great weight of guilt off my shoulders: I can give in to the temptation to write interesting programs, and still remain morally as pure as the driven snow.

]]>

For example, the Galois connection determining integer division that we considered a couple of posts ago

defines to be the greatest solution to the equation . It does so in a very pithy way: reading the equivalence as an implication from left to right, instantiating to (and exploiting the reflexivity of the ordering ), we get that , so is indeed a solution to the equation on the right; reading the equivalence from right to left, we get that for any solution , so is in fact the greatest solution.

Similarly, the characterization of the floor function from reals to integers

defines as the greatest integer for which , and the Galois connection involving and

characterizes as the greatest set (under the usual subset ordering) for which .

The characterization of greatest solutions might be equivalently expressed in terms of *greatest lower bounds*. Given a preordered set , and a subset of , an element is a *lower bound* of in if for every ; in addition, is a *greatest lower bound* of if for any other lower bound . (Note “a” rather than “the”, as there may be multiple such. But they are all related by ; if the ordering is a partial order, the is unique when it exists. Note also that need not be in itself, even when it does exist.)

This construction can be phrased in terms of Galois connections as follows. The two ordered sets are and , where is the set of *nonempty* subsets of , with ordering defined pointwise: iff for all . The mappings in either direction are the singleton set former and greatest lower bound , related by the Galois connection . Here’s how it looks with and :

The categorical perspective on greatest lower bounds is the notion of *limit*; it’s just the generalization of the diagram above to an arbitrary category. Here is a very brief outline. The fragment of the diagram consisting of is called a *cone*, from vertex to base (and so is ). The cone is called a *limit* when, for any other cone from vertex to the same base, there is a unique arrow making the diagram commute.

Commutativity of the diagram above isn’t very interesting—because the category is a partial order, but also because the base is degenerate: just three discrete objects. In general, the base will also contain arrows; then a cone consists of a vertex ( in the diagram below) with arrows to each of the objects in the base () making the diagram commute (, etc). As before, the cone from vertex is a limit if any other cone factors uniquely through it.

Of course, it all dualizes beautifully. The categorical perspective on least upper bounds is expressed in terms of cones *from* a base ( below) to a vertex (), being a *colimit* if allowing unique factorization for any other cone from the same base to another vertex ().

Recall that, for a functor , an *-algebra* is a pair consisting of an object and an arrow . A *homomorphism* between -algebras and is an arrow such that:

The -algebra is *initial* if there is a unique such for each . We usually write for the “carrier” of this initial algebra (because it is the “least fixed point” of , as we shall see below), and for the “constructor” (and indeed, it is an isomorphism, so a constructed piece of data can be deconstructed again); we write for the unique such that .

As you might expect, “initial” things are extreme solutions too, albeit not in a very interesting way. An *initial object* in a category is an object from which there is a unique arrow (often written ““) to any other object. An initial object is a colimit of the diagram generated from the empty category—which has no objects, and hence no arrows either. (Any object forms the vertex of a (trivial) cone, so the colimiting vertex is simply one from which there is a unique arrow to any other vertex, with no additional constraints.) In particular, an initial -algebra is an initial object in the category of -algebras, whose objects are -algebras and whose arrows are homomorphisms between them.

And of course, it all dualizes nicely, to final coalgebras, which are in some sense “greatest fixed points” of functors; final objects are the vertices of limiting cones *to* the empty base.

Here is a more illuminating presentation of initial algebras as extreme solutions, explaining rather better in what way they correspond to “least fixed points” of functors. (The construction is well known; I’ve based this presentation on a manuscript by François Métayer.) Initial algebras can be constructed as an instance of the colimit construction above, in which the base consists of a *countable chain* of objects and arrows:

In the category , every such a chain has a colimit (categories with this property are called *-categories*).

If the category has an *initial object* , then any endofunctor induces such a countable chain:

Under mild assumptions, the colimit of this chain is (the carrier of) an initial -algebra. (Besides assuming an -category with an initial object, we have to assume that is *-cocontinuous*—that is, that it transforms the colimit of the countable chain into a colimit of the countable chain . One can show that any *polynomial functor*—one built from constants using sum and product—is -cocontinuous.)

The construction goes as follows. By assumption, the countable chain has a colimit; let’s suggestively call the vertex , so that the edges satisfy for each .

Since is -cocontinuous, it transforms this diagram into another colimiting cone, with base shifted one place to the right and vertex . But is the vertex of another cone over the same shifted base; and since is the colimit, there is a unique arrow—let’s suggestively call it —making the diagram below commute ( etc).

All we have to do now is to show that is indeed the initial -algebra, as claimed. Suppose we are given another -algebra ; we will (i)~construct an arrow , (ii)~show that it is a homomorphism between the algebras, , and (iii)~show that it is the only such.

For (i), given the target -algebra , we can construct a square as follows:

which commutes by virtue of the initiality of . Applying to this square yields another, which can be pasted alongside; and this can be repeated indefinitely, yielding the following ladder:

Then we can pick out arrows . Moreover, these s commute with the base of the colimit diagram (, etc) to yield another cone to vertex ; we therefore conclude that there is a unique such that for each .

Now for (ii). Note that and the also form a cone over the shifted base starting from ; and because is the colimit from this shifted base, we also get a unique mediating arrow such that for each .

Moreover, both and are also such mediating arrows:

so both must equal and hence also each other: .

Finally, for (iii), suppose we have another for which ; we have to show that . By the uniqueness of the mediating arrow, it suffices to show that for each , which is easily done by induction.

That is, given -algebra , there exists a unique (for which we write ““) such that . If you squint at this in the right way, you can see the inductive definition of the recursive datatype, and of the folds over it. Each is an approximation to , cut off at depth ; they all embed into , and indeed, is the least extension—the colimit—of them all. Each is an approximation to , again restricted to data structures cut off at depth , and is the completion of all the .

Naturally, it all dualizes for final coalgebras: then we need “cochains” to a terminal object ; an -category is one in which all such countable cochains have a limit; -continuous functors preserve limits of countable cochains. (It is a bit unfortunate that the interesting extreme algebra, namely the initial algebra, is a *co*limit, whereas the final *co*algebra is a limit, but sometimes life is like that.)

The definition of limits can be made more concise and precise by noting that the base corresponds to the image of some functor , where is the category of interest, and *index category* determines the shape of the base—for each object of , there is an object of in the base ( in the diagram below), and for each arrow of , an arrow of in the base ( below).

(In the diagram, the index category is the discrete category on three objects—with no arrows other than identity arrows. In the diagram above, is , with three objects and two generating arrows. In the construction of initial algebras, the index category is , equivalent to the usual ordering on the natural numbers, whereas for final coalgebras it is , equivalent to on natural numbers.)

The vertex too can be seen as the image of under a particular, degenerate functor—the diagonal functor , defined by for each object of , and for each arrow . Then “the cone from vertex to base ” corresponds to a natural transformation : naturality is exactly the condition that the cone commutes. We write “” for the limiting object, ; its universal property is that, for any cone from to , there exists a unique such that for each . In other words, there is a (natural) isomorphism between the natural transformations and the arrows ; that is, an adjunction , with limit being right adjoint to the diagonal.

Dually, of course, colimits turn out to be left adjoints: the whole construction is encapsulated in three symbols, .

]]>

Two functors and form an adjunction, written , if there is an isomorphism between the sets of arrows in and in . We say that is the *left adjoint* and the *right adjoint*. The essence of the isomorphism is captured by two natural transformations in and in , called the *unit* and *counit* of the adjunction; is the image in of in , and conversely, is the image in of in . The unit and counit satisfy the laws

From them one can construct the witnesses to the isomorphism for arbitrary arrows: for each arrow in , there is a unique arrow in such that , given by ; and conversely, for each arrow in , there is a unique arrow in such that , given by ; and moreover, these two constructions are each other’s inverses.

A preorder forms a category: the objects of the category are the elements of the set~, and between any two elements , there is a unique arrow if , and no arrow otherwise. That adjunctions are a generalization of Galois connections follows straightforwardly from the fact that there is at most one arrow between any two objects in a preorder category. Then monotonic functions and between preorders and form a Galois connection precisely if the sets of arrows and are isomorphic—that is, if both and hold, or neither do, or in other words,

A very useful example of adjunctions arises in the definition of products—in the category of sets and total functions, for given types , there is an isomorphism between the set of pair-generating functions, of type , and their two projections, pairs of functions of types and . (Indeed, given functions and , one can construct the pair-generating function ; and conversely, given a pair-generating function , one can construct its two projections and ; and moreover, these two constructions are inverses.)

The “isomorphism between sets of arrows” can be elegantly expressed as an adjunction; since it concerns pairs of arrows, one side of the adjunction involves the product category . The right adjoint is the product functor , mapping an object in —that is, a pair of sets—to their cartesian product as an object in , and an arrow in —that is, a parallel pair of functions—to a function in acting pointwise on pairs. In the other direction, the left adjoint is the *diagonal* functor , mapping an object in to the object in , and a function to the pair of functions as an arrow in . The adjunction amounts to the isomorphism

or equivalently,

The unit and counit of the adjunction are and . In more familiar terms, the unit is a natural transformation in , so a polymorphic function; in fact, it’s the function of type that we might call . However, the counit is a natural transformation in , so not simply a (polymorphic) function; but arrows in are pairs of functions, so we might write this .

Then the “fork” operation is in fact one of the two witnesses to the isomorphism between the sets of arrows: given an arrow in , that is, a pair of functions of types , then is an arrow in , that is, a function of type , given by the construction above:

or, with more points,

The laws that the unit and counit satisfy are

or, in more familiar terms,

The universal property of follows from the isomorphism between sets of arrows:

The universal property of underlies all the useful laws of that operator.

Of course, the situation nicely dualizes too. Coproducts in arise from the isomorphism between the set of arrows and the pairs of arrows in and . Again, “pairs of arrows” suggest the product category; but this time, the diagonal functor is the right adjoint, with the coproduct functor (which takes a pair of sets to their disjoint union) as the left adjoint. That is, the adjunction is , and the isomorphism is

The unit is a natural transformation in , that is, a pair of functions and . The counit is a natural transformation in , which we might call . The “join” of two functions with a common range is a witness to one half of the isomorphism—given an arrow in , then is an arrow in , defined by

The two laws that the unit and counit satisfy are:

or, perhaps more perspicuously,

Another familiar example from functional programming is the notion of *currying*, which arises when one can construct the *function space* (the type of functions from to , for each type and ), such that there is an isomorphism between the sets of arrows and . Here, the adjunction is —in this case, both functors are endofunctors on . The unit and counit are natural transformations and . We might call these and , since the first is a curried pair-forming operator, and the second applies a function to an argument:

The laws they satisfy are as follows:

or, in points,

The isomorphism itself is witnessed by the two inverse functions

where and .

]]>

The universal property of the operation for products is a representative example. Recall that when and ; and that and . Then is completely defined by its universal property:

This identity repays careful study.

- It translates a problem in the more complex domain of products (namely, the problem of showing how some complicated expression can be written in terms of ) into simpler problems (here, equations about the two projections of ).
- It’s an equivalence. So not only do you have an implication from left to right (any expressible as a satisfies the two properties on the right), you also have one from right to left (any pair of functions satisfying the two properties on the right induces a ). In other words, is a solution to the equation on the left iff it is a solution on the right; not only does a solution on the right yield a construction on the left, but also the absence of solutions on the right implies the absence on the left. Or again: the equations on the right have a unique solution in —since any two solutions must both be equal to the same expression on the left.
- It has many useful simple consequences. You can make the left-hand side trivially true by letting ; then the right-hand side must also be true:

Symmetrically, you can make the right-hand side trivially true by letting and ; then the left-hand side must also be true:

If you further let , you conclude that every pair consists solely of its two projections, nothing more:

In fact, the universal property of tells you everything you need to know about ; you might take that as one justification for the term “universal”.

- It also has many useful less obvious consequences. For example, if you’re searching for an that acts independently on the two components of a pair— and —just let and in the universal property, and conclude

(which we’ve written “” elsewhere). For another example, we can deduce a fusion law for : for what does the equation

hold? This matches the left-hand side of the universal property; expanding the right-hand side yields

Such a rich harvest from so small a seed! (In fact, we will see later that an even smaller seed suffices.)

We can see the same structures that occur in universal properties like that of above also in relationships between orderings. As a very simple example, consider the problem of dividing a natural number by two, exactly; the universal property of a solution to this problem is the equivalence

That is, is a solution to the problem “compute ” precisely when ; both the existence and the identification of a solution to a problem expressed in terms of division has been translated to one in terms of multiplication—which is arguably a simpler setting. Note that the universal property amounts to an equivalence

involving the two functions and , which are in some sense inverses. This pattern will crop up over and over again.

The division example involved an equivalence between the two identities and . More generally, another relation than “” might be involved. Extending the previous example to integer division, rounding down, we have for :

Again, this relates the two (in some sense inverse) functions and ; but this time equality is inadequate for stating the problem, and it perhaps more convincing to claim that a more complicated problem has been translated into a simpler one . What is more, translating the problem via this universal property pays dividends when it comes to reasoning about the problem, because the simpler problem space is much more amenable to calculation. For example, properties of repeated division (for ) do not trip off the tongue; but we can reason straightforwardly as follows:

Thus, precisely when , or in other words, .

In this case, the two problem spaces have both involved the same relation on the same domain, namely the natural numbers; that is not essential. For example, the universal property of the floor function from reals to integers is given by:

where, to be completely explicit, we have written for the usual ordering on reals and for the corresponding ordering on integers, and for the injection from the integers into the reals. This time the two problem spaces involve two different orderings on different domains; we say that the pair of functions and form a *Galois connection* between the orderings and . (We also see that the relationship between the two functions and is becoming less like a pure inverse relationship, and more of an embedding–projection pair.)

As a simple non-arithmetical example of a Galois connection on a single domain, consider some set and a fixed subset ; then

That is, and form a Galois connection between and itself.

A non-arithmetical example between two different domains is afforded by the field of *formal concept analysis*, which relates “objects” and their “properties”. Given are sets of objects and of properties, and a relation ; we write to denote that object has property . This induces “concept-forming operators” and defined by:

That is, is the set of properties enjoyed by all objects in , and is the set of objects enjoying all the properties in ; a *concept* is a pair with and . The concept-forming operators form a Galois connection between and :

This construction can be used to translate a problem about the extension of a concept (that is, an enumeration of its instances) into one about the intension (that is, the characteristic properties of its instances). It is related to the observation that “syntax and semantics are adjoint“—under the analogy that “objects” are sets of mathematical structures, “properties” are axioms, and the relation is “satisfaction”, the models of an axiomatic theory are included in a set of structures if and only if the theory logically entails the minimal axiomatization of .

]]>

While there, I reported on a marvellous observation made by Russell O’Connor, that lenses are exactly the coalgebras for the costate comonad. That is, the independently identified notion of a “very well-behaved lens” in the work of Pierce and others coincides exactly with the categorical notion of a “coalgebra” for a particular comonad, the “costate” comonad. I’ll unpack that claim here.

Pierce’s lenses are pairs of functions between “source” and “view” datatypes and : a “get” function and a “put” function . The story is that the view is some projection of the data in the source—perhaps a subset of the data, or the data in a simpler format—and so in order to update the source given a modified view, one needs also a copy of the original source from which to reconstruct the missing information.

For these two functions to capture a “well-behaved” lens, they should satisfy the so-called Get–Put and Put–Get laws:

The Get–Put law says that if you “get” a view of the source, and then “put” it straight back without modifying it, the source remains unmodified: a no-op edit on the view translates into a no-op on the source. The Put–Get law says that if you “put” any view into a source and then “get” it back, you end up with the view you first thought of: nothing is lost from the view when it is put back.

Additionally, for these two functions to capture a “very well-behaved” lens, they must satisfy a third law, the Put–Put law:

In words, “put”ting back two views then is equivalent to “put”ting back just the second; any changes to the source from putting back are completely overwritten when putting back . (This turns out to be rather a strong condition, requiring that the source basically factors into the view and a completely independent “complement”; few real applications of bidirectional transformation satisfy it. But that’s another story.)

Intuitively, comonads capture “data in context”. A comonad consists of a functor together with two natural transformations and that extract the data from its context and duplicate the context, satisfying the three axioms:

One example of a comonad is the “costate” construction: for fixed , define functor by

so that the “map” function for satisfies . The operations are given by

Verifying that these definitions satisfy the comonad axioms is left as an exercise for the interested reader.

(Incidentally, I think it’s called the “costate” comonad more because it is the dual of the “state” monad , rather than because it has anything to do with stateful computations. However, it does model state in the sense of stored variables; and indeed, Russell O’Connor’s blog posting calls the “store” comonad.)

For a functor , an -coalgebra is a pair of a type and a function . A “coalgebra for a comonad ” is a -coalgebra that interacts well with the operations and of the comonad; that is, the function should also satisfy the laws:

(Another incidentally: I don’t have a feeling for what these laws mean, in the way that I do for the laws of an algebra of a monad. At least for the free monads that represent terms with free variables, an algebra is a pair such that makes sense as an “expression evaluator”—it respects singleton variables and substitution. It’s clear to me that the laws of a coalgebra for a comonad are the obvious duals of those for the algebra of a monad; and that they describe the interesting ways of putting together the coalgebra operation with the comonad operations; but I still don’t have a direct intuition. Any comments gratefully received!)

Now it’s just a matter of putting the pieces together. Curry the “put” function of a lens to obtain , and define a lens to be the fork of the “get” and “put” functions:

Note that now where is the costate comonad. The Get–Put law is equivalent to the counit axiom of the coalgebra:

And the Put–Get and Put–Put laws together are equivalent to the coassociativity axiom:

]]>

This post will involve some language that we have not yet covered. Fear not! I hope it will be clear from context. But in case it isn’t, you might want to take a look at some of the background material (especially the paper Calculating Functional Programs).

Like Nick, for simplicity we will take the datatype of streams to be a synonym for lists; in all that follows, assume that lists are properly infinite (not finite, or partial).

Streams are naturally a codatatype rather than a datatype: in the category of sets and total functions, they would be represented as a final coalgebra rather than an initial algebra. In Haskell, which is roughly based on the category of CPOs and continuous functions, initial algebras and final coalgebras coincide, so we need not (indeed, we cannot) make the distinction formally. But we can make it informally, by stipulating that the basic pattern of computation for streams is the :

generates a stream from a seed, using the body that transforms a seed into an element and a new seed . For example, the map function for streams uses the input stream as the seed, repeatedly splitting it into its head and tail:

where applies two functions to the same argument:

The crucial property of is its *universal property*, which provides necessary and sufficient conditions for a computation to be expressible as an instance of :

where deconstructs a stream into its head and tail, and

From the universal property, one can easily (exercise!) prove three simple consequences (we’ll call them the “identity” and two “evaluation” rules):

and the very important *fusion law*:

allowing a preceding function to be absorbed into the unfold.

Making streams a monad amounts to defining functions

satisfying the monad laws:

Looking at the type, the obvious (indeed, I think the only possible) definition one can give for is where

and makes two copies of its argument. However, there are many type-correct definitions one could give for , including , , and , where

and where (for brevity in what follows) we define

Obviously, yields the first “row” of a stream of streams (if one considers it in row-major order), and yields the first column; as the name suggests, yields the leading diagonal. Nick’s post demonstrates that the first two, although type-correct, do not satisfy the monad laws. He also provides a proof that the third does, which we turn to next.

The proofs that and satisfy the three monad laws are very straightforward, using the universal property of and its consequences.

For the first monad law, fusion gives us the condition to check:

Working on the right-hand side, we have:

discharging the proof obligation.

Similarly, for the second monad law, fusion gives us the condition:

and working on the right-hand side, in almost exactly the same steps we get:

discharging the obligation.

What about the third monad law? To apply the universal property (or fusion), we need one side to be expressed as an unfold; but neither side of the equation is in that form. No matter; let us hypothesize that one side—say, the left—can be expressed in the form for some , then calculate a suitable definition for (if one exists). Assuming we succeed, then we can use fusion to check that the other side equals . (This strategy doesn’t work if we can find no such !)

Again, fusion gives us

so we calculate:

Therefore, letting

we have concluded that

Now all we have to do is to check that the right-hand side of the third monad law also equals this; fusion gives us the condition

and we calculate on the right-hand side:

completing the proof.

As you’ll see, the calculations are all quite short and simple, whereas in Nick’s formulation, they were rather hard work; I think that was (a) because he wasn’t exploiting the universal property, and (b) because he was working in terms of the “bind” rather than the “join” of the monad, which forced him into a more pointwise rather than pointfree style. Points are helpful when writing programs, but less so when reasoning about them.

Here’s another way of looking at the problem. Nick’s blog presented three plausible (that is, type-correct) definitions for the operation. Two of these didn’t satisfy the necessary laws, so were evidently wrong. The third, , does satisfy the laws, but is it the only possible definition that does? I believe that it is the only solution in the form of an unfold; but I only have a hand-waving argument as to why.

Let us suppose that indeed

for some . Without loss of generality, let us suppose also that

with

I claimed above that is the only type-correct definition of the operation. (Ignoring bottoms, that is. Which is to say, in Haskell, all type-correct definitions are approximations in the definedness ordering to .)

Consideration of just the first two monad laws gives us some constraints on , since we know that :

Or in terms of ‘s two components,

I claim that (1) entails that picks some element out of the first “column” of a stream of streams (thinking of the input as an infinite matrix in row-major order again)—for the equation says that when the input consists of infinitely many copies of the same stream, picks (one of the many copies of) the head of that stream. Symmetrically, (3) entails that, when given a infinite matrix whose columns are all equal, picks some element out of the first “row”. And because has to be polymorphic, it cannot behave differently on special matrices like these than it does in general. Putting those statements together, and waving my hands in the air, I conclude that picks the only element that is in both the first row and the first column:

Similarly, Equation (2) says that, given an infinite input matrix all of whose rows are equal, drops the first column (and possibly some of the rows are duplicated or dropped, and the order of the rows may change; but the elements of the rows are untouched). Symmetrically, (4) says that, given an input whose columns are all equal, drops the first row (and may duplicate, drop, or rearrange the columns, but not change any of them). And again, the behaviour in general must be consistent with these special cases. Putting these observations together, must drop the first row and the first column, and cannot change any of the remainder of the matrix.

What is the right framework in which to present such arguments more formally? It feels rather like Paul Hoogendijk’s relational approach to generic programming, which has to talk about largest natural transformations of a given type: the relational setting provides the conjunction one needs in order to express the two separate constraints on .

]]>