Link to this sectionChurch Encoding, Parametricity, and the Yoneda Lemma
I still remember the shock I felt when I first encountered functional programming years ago. That was the moment I learned that natural numbers can be built within the language itself:
data Nat = Zero | Succ NatI went on to learn that all computation can be expressed through functions (the lambda calculus), that recursion itself can be encoded as the mind-bending Y combinator:
Y = λf. (λx. f (x x)) (λx. f (x x))And then there were Church numerals, where each number becomes a function:
0 = λs. λz. z
1 = λs. λz. s z
2 = λs. λz. s (s z)Church encoding represents natural numbers as functions; each number takes a successor function and a starting point, then applies the successor times.
But what is the reasoning behind it? Why these particular lambda terms?
There is also Church encoding for lists:
nil = λc. λn. n
cons = λx. λxs. λc. λn. c x (xs c n)The pattern feels similar, but the details are different. For a long time I assumed this was just how things were: a clever trick, rediscovered case by case.
It is after many years of learning that I finally understand the deeper story. Church encoding manifests deep connections between data types, polymorphism, and category theory. Once you see the connections, the encoding’s shape stops being a trick and starts being inevitable.
I want to trace those connections here. We’ll start with the simplest data types, watch a pattern emerge, and build up the machinery: parametricity, algebraic data types, F-algebras, the Yoneda Lemma, until Church encoding looks less like a clever trick and more like something the math demands.
Link to this sectionSystem F
To capture the pattern behind Church encoding, we need types. The untyped lambda calculus gives us the terms, but it gives us no vocabulary to say what those terms are. That’s the Simply Typed Lambda Calculus (STLC), where every term has a type. The only type constructor in bare STLC is the function arrow 11.To be precise, STLC also includes some base types, like or otherwise you cannot give the parameter of the innermost function a type. But the particular choice of base types is irrelevant to the story; we just need something in the language to talk about..
But STLC hits a wall almost immediately. A Church numeral must accept any type as its carrier: the whole point is that works the same whether you’re counting apples or functions. STLC can’t say that. Every function in STLC has a fixed, monomorphic type.
This is where the experienced programmer sits up: we need generics. We need functions that are polymorphic over types. The calculus that gives us this is System F, the polymorphic lambda calculus.
In System F, a function can take a type as an argument. You write type abstraction as and type application as Types of System F include type variables function types and universal quantification 22.Unlike STLC, base types are not necessary in System F. The polymorphism alone gives us enough structure to build everything we need.
Our System F starts as an empty universe. In STLC, we would declare base types like and to get started. But in System F, it’s interesting that we can build these types from scratch, using only functions and polymorphism. We can encode and as polymorphic functions, without any special syntax for data types.
Let me state a principle: a data type can be equivalently represented by the ways you consume it. I can’t yet explain the logic behind this claim, but let’s set it aside and see how it works for 33.In the second half of this article, we’ll see the category-theoretic foundation for this principle. The Yoneda Lemma will show that the set of all ways to consume a type fully determines the type itself.
If you’re holding a value of type what can you do with it? The only way to consume a value is to ignore it and return something that has nothing to do with it.
Suppose you want to write a universal consumer: for any target type it turns a into an Because we know nothing about we cannot make up any new value of type The only thing we can do is to return an that we already have. But where do we get an from? We don’t have one! We should receive it as an argument. Therefore, the type signature of a universal consumer of is:
Read as: “for any type give me an and I’ll give you back an ”
What inhabits this type? It is easy to think of one: the identity function.44.Later we’ll see that this is the only possible implementation, as a consequence of parametricity. It takes an and returns it unchanged:
id = ΛX. λx. xThis function is the Church encoding of
Let’s try the same reasoning with has two constructors, and
What does consuming a require? You need a target type and you need an interpretation for and one for two values of type Then, depending on which constructor the actual value represents, you return the appropriate interpretation.
As a type signature:
∀X. X → X → XRead as: “for any type give me two s and I’ll give you back an ”
We can find two inhabitants of this type, which correspond to the two ways to consume a
true = ΛX. λx. λy. x
false = ΛX. λx. λy. yOne chooses the first argument, the other chooses the second. They correspond exactly to the two values of
Looking at these two examples, a pattern emerges:
The Church encoding of a data type in System F is a polymorphic function whose arguments match the constructors. It is a universal consumption interface for the type. This works perfectly for and whose constructors carry no data. But what about a type like the ? Its constructor has a recursive parameter. We’ll handle recursion soon. But before we do, we need to understand the mechanism that makes the pattern work in the first place.
Link to this sectionParametricity
What’s striking is that for we can only find a single implementation, the identity function. Likewise, for we can only find two implementations, true and false. The type system of System F does not permit any other implementations.
Once you have convinced yourself of the fact, let’s move on.
To understand why the type system restricts the inhabitants so precisely, we need to examine the mechanism behind System F’s polymorphism. The polymorphism in System F is parametric: a polymorphic function gets a type argument, but it can’t inspect it. It can’t branch on “am I dealing with Int or Bool?” It must treat the type as a black box. That restriction turns out to be the source of enormous power.
John Reynolds proved the parametricity theorem (also called the abstraction theorem) in 1983. Here is a compact statement:
Let be a closed term of System F, where is a type expression. For any types and any relation let be the relational lifting defined recursively from the structure of then
The formulation looks abstract, but the message is simple: a polymorphic function must “preserve” whatever relation you associate with the type parameter. It cannot detect the concrete structure of the type it’s instantiated with. A consequence is that you can derive equations the function must satisfy purely from its type signature, regardless of implementation. Philip Wadler later called these “theorems for free.”
We’ll start with a special case you can verify by hand.
Claim: has only the identity function, i.e., any must satisfy for all and
Proof: Take two arbitrary types and and pick any relation between them. The theorem requires us to lift through the type expression The lifting works like this: two functions and are related by precisely when they map -related inputs to -related outputs, that is, whenever Intuitively, and preserve in lockstep.
Now, parametricity says: because is polymorphic, its instantiations at and must be related by this lifted relation. In symbols: Spelling that out: for any we have
Here comes the trick. Fix a type and a value We want to show Define a very specific relation that pairs with itself and nothing else:
Take Since parametricity forces:
But contains exactly one pair: So must be Done.
Parametricity forced to be the identity function. knows nothing about the type it’s applied to; the type signature alone left it no other choice.
A similar argument works for A function of this type receives two values of an unknown type and must return an With no operations available on the only possible behaviors are “always return the first argument” or “always return the second.” That’s true and false.55.A formal proof follows the same relational strategy, using for two distinct values
Now let’s look at the general shape . Here is any type operator; think of it as describing the structure of a data type. The free theorem we get is this: for any F-algebra homomorphism66.We’ll explain what an F-algebra homomorphism is later.
This equation will play a central role later when we prove that Church encoding is equivalent to the data type it encodes.
Link to this sectionAlgebraic Data Types and Functors
With parametricity in our toolkit, we now return to the main thread. Recall where we left off: and revealed a pattern (Church encoding is a polymorphic function whose arguments match the constructors), but we had no way to handle recursive types like To extend the pattern, we need a systematic language for describing the structure of data types — something that makes constructors and their arguments explicit. This is where algebraic data types (ADT) come in.
We know that tuples are product types and tagged unions are sum types. An algebraic data type is built from these two operations, fundamentally, as a sum of products. Each constructor is a product of its fields; the whole type is the sum among constructors. If a constructor carries no data, it is the empty product, i.e., the type.
We can make this precise with a small algebraic notation:
- (the unit type, ): a type with exactly one value. It is the identity of the product:
- (the sum type): a value is either an or a tagged with the choice.
- (the product type): a pair of an and a
Under this notation:
The last line reads: a natural number is either (the branch, carrying no information) or (wrapping another ). The equation is recursive, and we make sense of it with the binder:
The same recipe works for lists:
Here, is the branch and is the branch.
But the algebra goes deeper than notation. Types surprisingly obey the familiar laws of algebra. For example, the distributivity law:
Here denotes type isomorphism: there exist functions witnessing the equivalence in both directions.
Read the law as types: (a, Either b c) is isomorphic to Either (a, b) (a, c). As evidence, we can write the following functions:
f :: (a, Either b c) -> Either (a, b) (a, c)
f (a, Left b) = Left (a, b)
f (a, Right c) = Right (a, c)
g :: Either (a, b) (a, c) -> (a, Either b c)
g (Left (a, b)) = (a, Left b)
g (Right (a, c)) = (a, Right c)What about function types? Can we express them in terms of algebraic operations?
Let me declare: functions are exponents. Consider two finite types and with and inhabitants respectively. How many functions exist? For each input we can independently choose any output That’s choices repeated times: possibilities. This suggests writing the function type as an exponential:
Currying then becomes the familiar exponent law:
And functions out of sums follow their own distributive law:
Now let’s return to the Church encoding of natural numbers. We have seen Church numerals in untyped lambda calculus:
0 = λs. λz. z
1 = λs. λz. s z
2 = λs. λz. s (s z)We want to give them types in System F. Assume the type of z is We expect the type of 0 and 1 to be the same, so term s z should have the same type as z. Therefore, s must have type That gives us the Church encoding type for natural numbers:
It looks somewhat different from the Church encoding types for Unit and Bool. The second argument is a function rather than a value. Is there a single shape that captures all of them?
Let’s inspect the inner part of the encoding more closely.
Currying tells us that a function is equivalent to a function And we already know that the tuple can be written as and the function type can be written as Then we can do some algebraic manipulation:
So the full Church encoding becomes:
Look at the expression That is precisely the body of the recursive type definition of In other words, the Church encoding is of the form:
Here, is a functor that captures the shape of the algebraic data type. Let’s check that this holds for our earlier examples:
- For the functor is Then Matches
- For the functor is Then Matches
Here we get the general pattern: for an algebraic data type its Church encoding is
In the next section, we’ll see that is the type of universal consumers of F-algebras, and this is the perspective that will lead us, via parametricity and the Yoneda Lemma, to the deepest understanding of what Church encoding really is.
Link to this sectionF-Algebra
We’ve arrived at a turning point. The last section ended with a shape, that unifies the Church encodings of and But the shape still feels pulled from thin air. Why this particular arrangement of symbols? To answer that, we need to give names to the pieces. Category theory enters here.
A category is a collection of objects and arrows between them, with sensible rules for composition and identity. For a programmer, the natural example is the category objects are types, arrows are functions, composition is function composition, and the identity arrow is id.
A functor is a mapping between categories. In our world, maps each type to a type and each function to a function preserving composition and identity:
This is what the in has been doing: it builds a new type from an old one, and it lifts functions to act inside that structure.77.For given maps to and to This function-lifting is the machinery behind structural recursion; we’ll return to it when we define folds.
A natural transformation between two functors and is a way of turning shapes into shapes, uniformly for all types. For each type you have an arrow and for every function the following square commutes:
That is, This is naturality: the transformation must work the same way no matter which object you look at. Here’s the connection: the free theorems we got from parametricity are naturality conditions in disguise. A polymorphic function in System F is a natural transformation when viewed through the right categorical lens. Parametricity and naturality are two sides of the same coin.
With these three concepts — category, functor, natural transformation — we can finally name the pattern that has been staring at us since the very beginning. An F-algebra is a triple consisting of a functor a carrier type and a function
Intuitively, is an evaluator that folds the structure described by into a single value of type For example, the functor of natural numbers is An F-algebra for this functor consists of a type and a function By algebraic manipulation, this becomes a pair of functions where
- gives what the zero value evaluates to, and
- maps the evaluation of to the evaluation of its successor.
For a -algebra is simply two values of type the algebra map corresponds to a pair where evaluates true and evaluates false.
The Church encoding type now acquires a precise meaning: it is a universal consumer of F-algebras: given any F-algebra it takes the evaluator and runs it on the data type’s structure to produce a value of type It makes the “consumption interface” idea rigorous.
F-algebras for a fixed functor themselves form a category. An arrow in this category is called an F-algebra homomorphism. If and are two F-algebras, a homomorphism between them is a function that preserves the algebraic structure:
In diagram form:
The condition says: evaluating a structure in and then translating the result to yields the same value as translating the sub-structure to first and then evaluating in The two paths through the square produce the same result.
For example, for the homomorphism condition becomes:
These two equations are exactly the pattern that any structural recursion must obey: the base case maps to the base case, and the recursive case applies to the predecessor and then the successor function.
Link to this sectionInitial Algebra
Among the F-algebras for a given functor one deserves special attention. In a category, an initial object satisfies the initiality property: there is a unique arrow from it to every other object. In the category of F-algebras, the initial object is called the initial algebra, written where is the carrier and is the structure map.
By initiality, for any F-algebra there is exactly one homomorphism from to it. We call it
To get an intuitive grasp of what the initial algebra is, let’s look at the type of in System F. It takes an evaluator and returns a function So its type signature is
Compare this with the Church encoding type: They are almost identical. The only difference is that has an extra tucked before the final Where Church encoding takes an algebra and produces an fold takes an algebra and a value to produce an
This suggests a natural way to move between and Given we can partially apply to get a Church encoding: Conversely, given we can feed it the initial algebra’s own structure map: These two maps point at each other: one wraps a value into a universal consumer, the other unwraps a universal consumer by running it on the initial algebra itself. We’ll prove they are inverses, establishing
Before we do, we still need to understand what actually is. For that we return to initiality. Take the object and turn it into an F-algebra by using as the structure map. By initiality, we get a unique homomorphism from to this new algebra; call it But itself is a homomorphism in the opposite direction: Compose the two: is a homomorphism from to itself. Initiality says there is exactly one such homomorphism, namely so The same argument on the other side gives So and are inverses: is an isomorphism.
This is Lambek’s theorem: The carrier of the initial algebra is the recursive type That is why we choose the notation
Now that we know is a recursive type, the role of the structure map becomes clear. It is a constructor that builds the recursive type from its components. Take as an example, has two cases:
- means no predecessor: returns
- means one predecessor already built: returns
The fold equation now also becomes concrete. An algebra expands to a pair and the equation becomes:
This is structural recursion: replace every with every with an application of to the recursively processed predecessor. The fold walks through the value from the bottom up, substituting each constructor with the algebra’s interpretation.
One more consequence of initiality: Since is a homomorphism from the initial algebra to itself, and initiality says there can only be one, the fold at the initial algebra’s own structure map must be the identity. This equation unlocks the proof.
Stepping back: builds values from nothing. takes those values and interprets them in any algebra you choose, uniquely. One end generates; the other end consumes. We call this a universal producer.
The Church encoding is the mirror image: it takes any algebra and returns a value: a universal consumer. Universal producer meets universal consumer.
They are.
Let’s prove We define two functions between them in System F, and show that they are inverses of each other:
fromChurch : ChurchF → μ F
fromChurch c = c [μ F] in
toChurch : μ F → ChurchF
toChurch x = ΛX. λ(f : F X → X). fold f xfeeds the initial algebra to the universal consumer. takes a concrete value and turns it into a consumer by folding over any algebra you give it.
Step one: For any
Step two:
We need to show that for any any and any
This is where parametricity pays off. Recall the free theorem: for any F-algebra homomorphism
Let and Since is an algebra homomorphism, the free theorem applies directly:
That’s the equality we needed. Both directions are inverses, so
Two independent ideas: the uniqueness of the fold from the initial algebra and the free theorem from parametricity, interlocked to deliver the isomorphism.
We’ve proved the isomorphism. But a question lingers: why this shape? Why ? We arrived at it by following our noses through and a bit of algebra. That’s a fine derivation, but it doesn’t explain why the shape must be what it is. For that, we turn to what is arguably the most beautiful theorem in category theory.
Link to this sectionThe Yoneda Lemma
Before stating the lemma, one more piece of vocabulary. The Hom-functor embodies “the view from ” For any object is the set of all arrows from to which in is just the function type Given a function the Hom-functor maps it by post-composition: Formally: “everything you can do with an ”
Now the Yoneda Lemma:
For any (locally small) category any object in and any -valued functor there exists a bijection:
The left side is the set of natural transformations from to the right side is the value of at This bijection is natural in both and
Beneath the formalism, the idea is simple. A natural transformation from to is completely determined by a single choice: where you send Pick any element of as the image of and naturality does the rest — it uniquely transports that choice to every other object. Conversely, given a natural transformation, applying it to picks out an element of That’s the whole correspondence.
The Hom-functor captures everything you can arrow out of — the “outward view” of Yoneda says this outward view completely determines itself. Sound familiar? It’s the categorical incarnation of our consumption-interface principle: a type is fully characterized by how you can consume it.
Let’s make this concrete. Set to the identity functor where and to the category. The Yoneda lemma specializes to:
Unpacking the left side: is A natural transformation is a family of functions one for each So is necessarily a polymorphic function in System F. Its type is So Yoneda gives us the isomorphism directly.
For this says which simplifies to For we get These are exactly the Church encodings we derived by hand. Now they fall out of Yoneda for free.
But there’s a catch. This only works for non-recursive types: is a fixed type, not a recursive definition. To capture and we need to level up.
Instead of the category of types, we work in the category of F-algebras. The objects are F-algebras and the arrows are homomorphisms. In this category, the initial algebra is a distinguished object. Its Hom-functor maps any algebra to the set of homomorphisms from the initial algebra to it. By initiality, that set contains exactly one element:
Now introduce the forgetful functor which takes an algebra and discards the structure, keeping only the carrier It’s a functor from the F-algebra category to category.
Apply Yoneda with as the category of F-algebras, and
Let’s decode the left side. A natural transformation here gives, for each F-algebra a function from to But that Hom-set is a singleton, it contains only So specifying this function is equivalent to picking a value of type for each algebra. Let’s call it The naturality condition, with the algebra homomorphisms as arrows, becomes exactly:
For any algebra homomorphism
So the inhabitants of correspond precisely to the natural transformations on the left side of the Yoneda bijection. By Yoneda, they are in one-to-one correspondence with Therefore The universal shape of Church encoding, is the Yoneda representation of the initial algebra over the forgetful functor.
So the Church encoding is Yoneda in disguise. is the left side of the Yoneda bijection for the initial algebra over the forgetful functor, and Yoneda guarantees it’s isomorphic to
Parametricity and Yoneda are the same idea in two different languages. The free theorem is the Yoneda naturality square, instantiated in the category of F-algebras. The key proof step is Yoneda’s central move: determining the entire natural transformation from a single choice at 88.The two proofs run in parallel: is the naturality square applied to the homomorphism corresponds to Yoneda’s key step where determines the entire transformation. One path lives inside the type system; the other sits at a higher categorical level. They’re two views of the same structure. Parametricity is the type-theoretic shadow of categorical naturality.
Link to this sectionThe Final Recap
Church encoding begins with a simple intuition: a data type can be replaced by the way you consume it. From and this yields types like and To handle recursive types, we introduce functors that describe a data type’s one-layer structure, unifying all Church encodings under a single shape:
The inner part is an F-algebra, and the Church encoding is the universal consumer of F-algebras: it takes any algebra and produces a value. Among all F-algebras, the initial algebra (the recursive data type itself) is the key one: its unique fold operation gives us Meanwhile, parametricity forces polymorphic functions to behave as natural transformations, yielding the free theorem These two facts — one from initiality, one from parametricity — interlock to prove that Church encoding is isomorphic to the original data type:
The Yoneda Lemma tells us why. Applied in the category of F-algebras, Yoneda states that the natural transformations from the Hom-functor out of the initial algebra to the forgetful functor are isomorphic to itself, and those natural transformations are precisely the inhabitants of The Church encoding is a direct consequence of one of category theory’s most fundamental results. Parametricity and Yoneda are two views of the same structure: both rest on naturality, and one is the type-theoretic shadow of the other.
Returning to the Church numeral it is the Church representation of the initial algebra for the functor Church encoding is an elegant tool in programming, and its shape can be traced along a repeatable path from the consumption intuition all the way to the deep structure of category theory.