Traditional algebras deal with two things:
Example of an expression:
When we parse such an expression we create an expression tree. We start with
Expanding it recursively, we get
and are constants of type Double
. Variables like x
are strings. Plus and times are binary operators.
This is a recursive definition.
We have non-recursive leaves, Const
and Var
, and recursive binary nodes Times
and Plus
.
Our example is encoded as
which can be visualized as
An obvious choice to evaluate this expression is to turn it into a single Double
value.
We evaluate bottom up starting with leaves. A Const
leaf can be evaluated to the value it contains.
For evaluation purposes, the variable node can be assigned any value of type Double
, for instance x = 5
. For simplicity, we'll assume that any other variable is initialized to zero
In general, we can write many evaluators, or we can define an evaluator that is parameterized by the value of "x"
.
To evaluate the nodes, we have to first recursively evaluate the children nodes producing values of the type Double
The complete evaluator is then given by
But there are other choices for the result type of the evaluator, for instance, a string. A pretty printer is such an evaluator. The Const
leaf is evaluated to a string representation of the Double
it contains, a Var
leaf to the name of the variable, and the nodes are evaluated recursively
The problem is that different evaluators mix the recursive logic with the logic of combining the results of evaluating the child trees. We are repeating the same boilerplate. We would like to factor these things out.
When implementing an evaluator, we had to first choose the result type and then define a function of a particular type. We had a pair Double
and eval
and another pair String
and pretty
.
There are two orthogonal concerns here: one is the recursive nature of evaluation, and the other is combining the results of the evaluation at every step. If the children are evaluated to Double
, we add or multiply the numbers. If they are evaluated to String
we concatenate them with the appropriate operator symbol between them.
We'd like to create a data structure that would have placeholders for the results of the evaluation of the children. To do that, let's parameterize our Expr
by the result type R
The leaves have no children
whereas the nodes do
In the original recursive definition the children were full-blown expression trees; here they are replaced by values of some general type R
. R
can stand for the result of the evaluation, or it could stand for the whole expression–as we'll see later when we define a fixed point.
Altogether we get a data structure parameterized by R
With this definition we can implement our two evaluators as
Notice that these implementations are no longer recursive. The idea is that such evaluators deal with a single level (either leaf or node) of an expression tree. They assume that child trees have already been evaluated, and they only combine those results. They only implement the business logic of the evaluator.
But how do we use them to evaluate recursive expressions? For that we need a bit of category theory.
We now have two evaluators, one producing a Double
and another a String
. We know that there are functions that can turn a Double
into a String
. Can we use such a function, for instance toString
, to define a mapping of one evaluator to another?
We can try two different ways of doing that:
ExprF Double
, evaluate it using evalF
and then apply our function toString
to obtain a string.ExprF Double
, transform it to ExprF String
, and then use the evaluator prettyF
.In the latter, we have to transform ExprF Double
to ExprF String
. We can do this if ExprF
is a functor. And, indeed, it is
Note: we are using cats library instead of implementing our own functor.
We can now use map(_.toString)
to turn ExprF Double
to ExprF String
.
Unfortunately, the two ways of evaluating ExprF Double
to a String
produce different results.
For instance, take PlusF(1.0, 2.0)
evalF
to it. You get 3.0
, and then toString
turns it to "3.0"
.map(_.toString)
to it. You get PlusF("1.0", "2.0")
. Then prettyF
turns it to "1.0 + 2.0"
.Try it!
We have to conclude that these two evaluators cannot be transformed into each other using toString
in a consistent way. In other words, toString
doesn't preserve "the structure" of our evaluator.
On the other hand, some evaluators can be transformed into each other.
Here's an evaluator which produces a pair (String, Double)
We'll use the following function to map one type to another
We can check that the two ways of evaluating our test expression coincide
We'll say that mkDone
preserves the structure of the evaluator.
A combination of a type and an evaluator for a given functor F
is called an algebra
The type A
is called the carrier of the algebra, and the evaluator is called the structure map.
So far we've been concentrating on one such functor, ExprF
, but algebras can be defined for any functor.
We've seen three algebras for ExprF
, with the carriers, respectively, Double
, String
and (String, Double)
Functions between carriers that preserve the algebra structure are called algebra morphisms. We've seen one such algebra morphism, mkDone
that maps the ExprF
-algebra <Double, evalF>
to <(String, Double), evalPair>
. The function toString
, on the other hand, is not an algebra morphism.
The condition that has to be satisfied by an -algebra morphism corresponding to a function is often represented by a commuting diagram
where is the lifting of by functor (which is done with map
in Scala). We say that a diagram commutes if the two paths yield the same result. Here it is
In our example, was mkDone
, was evalF
, and was evalPair
. Composition of functions is written as and read "f after g". In Scala we often invert the order and say g andThen f
.
By pasting two such diagrams, we can easily convince ourselves that a composition of two algebra morphisms is again an algebra morphism. The outer rectangle commutes because the two squares commute
The identity function is also an algebra morphism
because , and using the fact that a functor acting on identity is again an identity.
Composition and identity are part of a definition of a category and, indeed, algebras and algebra morphisms for a given functor form a category (there is also the requirement of associativity of composition). The important part is that, in a category, we can define something called an initial object. Here, objects are algebras. An initial algebra is an algebra that has a unique outgoing algebra morphism to any other algebra.
If we call the initial algebra <I, j>
, with the carrier and the structure map
then for any other algebra <A, a>
we have a unique such that the following diagram commutes
This might seem unlikely, considering how hard it is to satisfy the commutation condition. But it turns out that our functor ExprF
has an initial algebra. In fact, we've seen it already: its carrier type is the recursive data type Expr
.
Indeed, we can easily define an evaluator ExprF Expr => Expr
The key result that explains this is the Lambek's Lemma. It states that the structure map (the evaluator) of the initial algebra is an isomorphism. Indeed, if you look at our implementation of j
, you see that it can be easily inverted. The proof of the Lambek's lemma is pretty straightforward and we leave it to the appendix.
Since is an isomorphism, we can write
In other words, is a fixed point of : the action of on gives us back the same .
This is how we can express the fixed point of a functor F
in Scala
The isomorphism is witnessed by two functions, in
and out
.
Notice that in
is the evaluator for the F-algebra with the carrier Fix[F]
, and out
is its inverse.
Fix[ExprF]
is equivalent to our recursive data structure Expr
. It contains exactly the same information.
We can define helper functions called smart constructors to help us build recursive expressions of the type Fix[ExprF]
Our original expression can be written as
These smart constructors can be also used to implement a mapping from Expr
to Ex
. We'll implement the inverse mapping later using a catamorphism.
By definition of an initial object, there exists a unique mapping from the initial algebra to any other algebra
Using Lambek's lemma, we can express the carrier of the initial algebra as a fixed point Fix F
, with the evaluator in
and its inverse out
By following the arrows, this diagram allows us to express m
, recursively, as a composition
The unique function is called a catamorphism for a given algebra. This formula translates directly to code.
Let's analyze what happens when we apply a catamorphism to a particular expression
First, we apply out
, which exposes the top level node
In this case, expr
was created by applying Fix
to a PlusF
node containing two expressions
Applying out
to it exposes PlusF e e'
.
We then apply the catamorphism to this node's children using _.map(cata(alg))
. This is where the recursion kicks in. But since the children are smaller than the original tree, the recursion is well founded–we are eventually bound to hit the leaves, at which point the recursion terminates (see the action of map
on leaves).
This recursive application reduces the children to values of the carrier type. We can then apply the evaluator to our top-level node and obtain the final value.
So that's the idea: you evaluate the children and then combine the results within a node. The recipe for combining the results is the algebra.
We are now ready to apply catamorphisms to the algebras we have previously defined. For instance, we can use our prettyF
to pretty print the expression
As we mentioned before, the conversion from the fixed point form to Expr
can also be done using a catamorphism
You can find the code here
Suppose that is the initial -algebra with the structure map . It means that for any other algebra there is a unique function such that the following diagram commutes
It so happens that is also an -algebra, because the lifting of has the right type
There must, therefore, be a unique algebra morphism from to it making the following diagram commute
We could draw another diagram
which trivially commutes, because the two paths are identical.
We can paste the two diagrams together to form a larger commuting rectangle
The bottom of this diagram, is therefore also an algebra morphism, but it's an algebra morphism from the initial algebra to the initial algebra. The initiality condition tells us that there can be only one such morphism, and we know that the identity function satisfies this condition. Therefore must be the same as the identity
We can now lift this equation to get
(functor laws ensure that the lifting of a composition is a composition of liftings, and that the lifting of identity is an identity). But we have established earlier that this diagram commutes
This is only possible if .
This proves that is both the left and right inverse of and, therefore, that is an isomorphism.