From Sets to Categories: Collections and Arrows
Part 1 of the “From Sets to Categories” series, exploring mathematical foundations through the lens of composition.
Preface
The details of sets and categories are not the point of this series, and you do not need to know any mathematics in advance. What matters is the shift in perspective they make possible. I came to that perspective in a couple of unexpected ways.
While I never excelled at or loved mathematics at school, I always found myself drawn to its patterns and logic in ways that I never truly understood at the time. Algebra was the first topic where I felt as though I could see the underlying structure more clearly. By dropping the numbers in place of letters, the underlying structure of the problem became suddenly clear and enjoyable rather than rote. I was even genuinely excited for the first mathematics lessons on Algebra, where solving for x became a kind of puzzle that I could approach with a sense of curiosity rather than mere calculation, and the time I was able to reach the solution felt rewarding in a way that simple arithmetic or any previous topics never really had. For the first time, maths didn’t feel challenging. I kept hoping we would get to something more complex or take the next natural step.
I was glad when letters appeared again later in the same school year, as we used them to label the sides of shapes in geometry, but rather than explore all the fun parts of this topic, such as discovering the fundamental relationships between angles, sides and vertices along with transformations and congruence, we were mostly asked to perform routine calculations with not much room for exploration. The underlying principles may have been stated quickly, but never truly explored, leaving me, at least, with the impression that the calculations were more important than understanding the concepts behind them. Most of the lesson time always seemed to be consumed by repetitive exercises rather than by discussions or explorations that could have deepened our understanding.
When I was taught column multiplication with decimals, I remember being shown a rigid, step-by-step algorithm that I was expected to follow without question, with marks awarded for working out. I felt constrained by my mental capacity to get through the steps mechanically, without truly grasping the underlying logic or reasoning behind them. Shawn had recently moved from Ireland and joined our class, where he sat next to me and noticed I was struggling with the method. He suggested I try what he called the “Chinese table method” for multiplication. I later learned it is more formally known as the lattice method. I was taken aback not only by the fact that he was getting out a ruler to draw a table just to multiply two numbers, but more by the realisation that it had never occurred to me there might be multiple methods for multiplying numbers when it got too complex to do it mentally. And yes, I now also understand that I had been stuck thinking mental multiplication was the only way to do it, when in reality there are often multiple valid approaches to solving the same problem, possibly one that you may find easier to reason about or more practical to use in different contexts. Shawn showed me how the table method worked, even getting told off for talking while we were supposed to be working, which I still feel bad about as he was probably the best-behaved kid I knew. I found the method quicker, simpler, and more enjoyable, mostly down to how visually simple it was to place the decimal point in the answer. I started using it everywhere and credit it with helping me scrape enough marks for an A in the GCSE non-calculator paper, despite the tight time limit.
Much later, while reading Unequal by Eugenia Cheng, I began to understand why Shawn’s lesson had stayed with me. It wasn’t only his kindness in showing me another way. He had shown me a different representation of the same operation, one whose structure made the operation easier for me to reason about. I would later encounter the idea of isomorphism: a structure-preserving correspondence that can be reversed. Perhaps that was my first lesson in category theory. I felt a little resentful at the time for not being taught that there was more than one valid method for approaching the same problem. I was most definitely not able to see that if this was the case for the multiplication of numbers, it could also be the case for other mathematical problems and beyond.
I won’t pretend to be a mathematician. My understanding of set theory and category theory is only at a surface level, but I find these ideas useful in life and in my work as a software engineer. So why learn something so abstract?
Concrete theories explain specific domains. Quantum mechanics models subatomic wavefunctions; Darwinian evolution models natural selection across breeding populations; compiler pipelines model token transformation into target bytecode.
Abstract theories are different. They do not describe a particular domain. Instead, they provide a formal language for constructing other theories. They are not tools designed to solve a single mechanical problem; they are the syntax with which tools themselves are defined.
Set theory and category theory are two influential abstract frameworks in modern mathematics. Since the late 19th century, set theory has been a widely used foundation for mathematics: in set-theoretic foundations, mathematical objects are represented in terms of sets and their elements.
In functional programming and other areas of computation, it is often useful to focus less on a collection’s individual elements and more on the transformations connecting collections.
These documents explore some basic set theory and category theory concepts, mainly for my own reference and understanding. Please consider that I approach this from a software engineering perspective rather than a purely mathematical one and may focus on aspects that are particularly relevant to computation and software design. I also include what I can only describe as many scary symbols and formal notations, and I don’t promise to define all of them rigorously or explore all their implications. But I will interrupt now and again to step back and relate the abstract mathematics to more concrete ideas grounded in our daily lives.
1. What is a Set?
Georg Cantor defined a set as “a gathering together into a whole of definite, distinct objects of our perception or of our thought.”
A set has no internal geometry. It has no ordering, no spatial positioning, no preference among its members, and no duplicated elements. Two sets containing identical elements are identical sets, regardless of how they are drawn or written down:
A set can also contain other sets. For example, has two elements, each of which is itself a set. There is nothing wrong with that. The trouble comes if we assume that any rule we can describe must define a set.
Think about the contacts in your phone for a moment.
If I ask which people are in your address book, it doesn’t matter whether you display them by first name or surname. The people haven’t changed. That is the part a set captures: membership, not presentation. If you care about who appears first, you need something more than a set.
However, mathematicians realized that naive set formation leads to paradoxes, such as Russell’s paradox. And when using sets to build the bedrock of mathematics, these paradoxes become problematic.
Suppose we try to make “the set of all sets that do not contain themselves”. Does that set contain itself? If it does, it breaks its own membership rule. If it doesn’t, it qualifies for membership, so it must contain itself. Either answer contradicts itself. That’s Russell’s paradox.
The problem isn’t sets containing other sets. It’s allowing unrestricted rules for forming sets. Zermelo–Fraenkel set theory, usually shortened to ZF, provides axioms that restrict set formation and avoid this paradox. Add the axiom of choice and you get ZFC. We could talk about extensionality, pairing, power sets, replacement…
But, I’ll stop myself there. I find that needlessly complicated. Not because those foundations are pointless, but because keeping all that machinery in my head doesn’t help me reason about the things I build. I’d rather put it to one side and ask: what can I connect, how do those connections compose, and what stays unchanged? I prefer thinking about the category axioms, which we’ll reach later in the series. They don’t do the same job as the set-theoretic axioms, but they give me a small set of rules I can actually keep hold of and reason about personally. For now, let’s get back to what we can do with a set.
In software, a type can be understood as a set of values:
Boolis the two-element set .Charis the set of all Unicode code points.Never(orVoid) is the empty set , containing zero possible values.
Subsets and Special Sets
From the basic definition of membership (), several foundational sets arise:
- Subsets: if every element satisfies . A subset lives entirely within the boundary of its superset.
- Singletons: A set containing exactly one element,
denoted
or
.
In programming, this is the
Unittype(): a type with only one possible value carrying no information. - The Empty Set (): The unique collection containing zero elements. Crucially, the empty set is a subset of every set:
Back to that address book.
Your emergency contacts form a subset of your contacts, provided they’re all in the address book. A group containing just Shawn is a singleton. A group with nobody in it is empty.
The empty group is a subset too: there isn’t anyone in it who could be missing from the address book. That’s all the slightly odd-looking statement above is saying.
2. Functions as Directed Relations
A set in isolation is static. To model dynamics, computation, and structure, we need relations between sets.
A relation between sets and could theoretically be anything: one-to-one, one-to-many, many-to-one, or many-to-many. But mathematics and computation center around one specific constraint: the function.
Definition: A function is a directed, many-to-one relationship from a source set (the domain) to a target set (the codomain) that assigns to every element exactly one element .
graph LR
subgraph Domain ["Domain A"]
a1["a₁"]
a2["a₂"]
a3["a₃"]
end
subgraph Codomain ["Codomain B"]
b1["b₁"]
b2["b₂"]
end
a1 -->|"f"| b1
a2 -->|"f"| b1
a3 -->|"f"| b2
Why did mathematics settle on this asymmetrical, many-to-one rule? Why not permit an input to yield two results, or allow an input to produce no result at all?
Because the entire architecture of reasoning and computation relies on determinism and composability. If can be both and , chaining operations branches into non-deterministic graphs. By requiring every source element to produce exactly one target element, functions become composable building blocks.
Imagine looking up a birthday.
Take the people whose birthdays you know as your input set, and calendar dates as your output set. Each person has one birthday, but several people can share a date. That’s allowed: different inputs can give the same answer.
If you don’t know someone’s birthday, the lookup isn’t a total function on all your contacts. You can restrict the input set, as we just did, or explicitly allow an “unknown” answer. The rule is about accounting for every input, not pretending missing information never happens.
The Identity Function
For every set , there exists a canonical function that changes nothing:
The identity function acts as the “zero” or neutral element of transformations. It represents the set itself within the realm of actions.
Edge Functions: Empty and Singleton Sets
The behavior of functions at the boundaries exposes the deep structure of sets:
- From the Empty Set: There exists a
unique function from the empty set to any set
:
Because
contains no elements, the condition “for every element in the
domain, assign an element in the codomain” is vacuously satisfied.
There are zero choices to make, making the function unique. In Haskell,
this is
absurd :: Void -> a. - To a Singleton Set: There exists a
unique function from any set
to the singleton set
:
Every element in
must map to the sole element
.
There is only one way to do this. In programming, this is the discarding
function
const ()or_ -> ().
3. Composition: The Core Primitive
Given a function and a function , an element maps to , which then maps to .
We can bypass the intermediate set entirely and define a new function:
graph LR
A((A)) -->|"g"| B((B))
B -->|"f"| C((C))
A -.->|"f ∘ g"| C
Composition is what separates mere data storage from engineering:
- In software, small pure functions compose into complex pipelines without intermediate state mutation.
- In mechanical engineering, standardized modules (pumps, heaters, grinders) connect sequentially to form an espresso machine.
- In linguistics and logic, premises compose into deductions.
Every time a transformation is established, any existing function yields a composite function .
Let’s put the arrows down for a second.
Imagine you have a distance in miles, a rule for converting miles to kilometres, and another for calculating a delivery charge from kilometres. You can connect the two rules to get a charge directly from miles. That is composition. We haven’t stopped doing the conversion; we’ve packaged both steps into one rule.
The important bit is that the steps fit. If the pricing rule expects kilometres and you hand it miles, the arithmetic might still run, but the answer will be wrong. Those source and target labels on the arrows are doing useful work.
4. The Law of Associativity
What happens when we compose three consecutive functions: , , and ?
We could group them in two ways:
- Compose and first to get , then compose with :
- Compose and first to get , then compose with :
Does the order of grouping matter?
graph LR
A((A)) -->|"f"| B((B))
B -->|"g"| C((C))
C -->|"h"| D((D))
A -.->|"g ∘ f"| C
B -.->|"h ∘ g"| D
A ==>|"h ∘ g ∘ f"| D
In set theory and functional programming, the answer is always no. Both bracketings produce the exact same composite transformation:
This property is associativity.
Associativity is the mathematical expression of reductionism. It ensures that complex systems can be parsed incrementally without ambiguity. It means we do not need nested parentheses when chaining transformations: is unambiguous.
Together with the identity law:
we have identified the two fundamental laws that govern functional transformations.
Grouping is not the same as order.
Suppose you tidy an address, format it as a label, and turn the label into a PDF. You could bundle the first two steps into an “address to label” tool, or the last two into a “label to PDF” tool. Either way, the same three steps happen in the same order.
Associativity says that changing those bundles doesn’t change the result. It does not say you can make the PDF before you have formatted the label.
5. The Shift: Internal vs. External Diagrams
Notice what happened as we moved from sets to composition:
- Internal diagrams require us to draw every dot inside a circle and connect individual dots with microscopic lines. They force us into the weeds of element-level bookkeeping.
- External diagrams zoom out. We replace the cloud of elements with a single labeled node (), and the bundle of element mappings with a single directed arrow ().
An external diagram does not reveal what is inside or . It treats objects as opaque black boxes and describes their behavior exclusively through the arrows entering and leaving them.
This shift in perspective defines the transition to category theory:
Category Theory is the study of structures that behave like functions: entities that connect sources to targets and compose associatively under identity.
Think about the London Underground map.
You don’t need a drawing of every seat and staircase to work out where to change trains. For that question, stations and connections are a more useful view than the contents of each station.
An arrow diagram makes a similar choice about what to show. It isn’t claiming that the contents don’t matter for anything; it’s helping us concentrate on connections. A transport map isn’t, by itself, the full definition of a category, but it’s a familiar reason to step back from the details.
In Part 2: Isomorphism and Structural Sameness, we explore invertible transformations, structural equivalence, and why category theory treats isomorphisms as equality.
Next in the series: Part 2: Isomorphism and Structural Sameness