~/ ~/documents ~/recommended-reading ~/software ~/pictures github (opens in new tab)

From Sets to Categories: Functors and Natural Transformations

Part 5 of the “From Sets to Categories” series, exploring mathematical foundations through the lens of composition.

What if I give you a whole page of phone numbers instead of just one?

Suppose we’ve agreed how to write a phone number neatly, with spaces in the right places. Now I hand you a list of them. You don’t need a new way to tidy a number; you apply the rule we already have to each one. If a form says the number is missing, there’s nothing there to tidy.

That’s where I want to start this last part: taking something we know how to do and using it in a different setting without having to invent it again. The names coming up are “functors” and “natural transformations”. Let’s give them something familiar to do before worrying too much about the names.

The previous parts of this series examined external arrows, isomorphisms, universal properties of products and sums, and the category axioms.

Up to this point, our scope remained bounded within a single category 𝒞\mathcal{C}.

Now we step back one level higher to examine relationships between categories themselves. This part introduces Functors and Natural Transformations.

1. Functors: Structure-Preserving Mappings

A category is a universe of objects and composable arrows. A Functor F:𝒞→𝒟F : \mathcal{C} \to \mathcal{D} is a structure-preserving mapping from category 𝒞\mathcal{C} to category 𝒟\mathcal{D}.

Formally, FF must:

  1. Associate each object A∈Ob(𝒞)A \in \text{Ob}(\mathcal{C}) with an object F(A)∈Ob(𝒟)F(A) \in \text{Ob}(\mathcal{D}).
  2. Associate each morphism f:A→B∈Hom𝒞(A,B)f : A \to B \in \text{Hom}_\mathcal{C}(A, B) with a morphism F(f):F(A)→F(B)∈Hom𝒟(F(A),F(B))F(f) : F(A) \to F(B) \in \text{Hom}_\mathcal{D}(F(A), F(B)).

while strictly preserving identity and composition:

F(idA)=idF(A)F(\text{id}_A) = \text{id}_{F(A)} F(g∘f)=F(g)∘F(f)F(g \circ f) = F(g) \circ F(f)

graph LR
    subgraph PerspectiveC ["Category C: Direct Reality"]
        A((A)) -->|"f"| B((B))
        B -->|"g"| C((C))
        A -.->|"g ∘ f"| C
    end
    subgraph PerspectiveD ["Category D: Contextual / Observed View"]
        FA(("F(A)")) -->|"F(f)"| FB(("F(B)"))
        FB -->|"F(g)"| FC(("F(C)"))
        FA -.->|"F(g ∘ f) = F(g) ∘ F(f)"| FC
    end
    PerspectiveC ==>|"Functor F"| PerspectiveD

Same town, different map.

Imagine we’ve spread two maps of the same town across the table. One shows every bend in the road and the outlines of buildings. The other is a simple drawing of junctions and the roads between them. We haven’t gone anywhere; we’re looking at the same place through a different window, or viewport.

That’s one way I like to picture a functor. Let’s use junctions as our objects and journeys as our arrows. For each junction on the detailed map, we choose its place on the simple one. For each journey, we show the corresponding journey there too.

There’s a promise to keep, though. If you travel to the shops and then to the station, the simple map must join those journeys up in the same way. It shouldn’t matter whether we redraw the whole journey at once or redraw the two parts and join them afterwards. And staying at home shouldn’t turn into a journey. Those are the two equations above, with places we might actually visit.

We might lose the shapes of the roads, so this needn’t be a change we can undo. Functors can also connect things that aren’t maps, or views of the same place at all. The maps are a way into the idea; keeping the connections working is what matters.

Functors as Structure-Preserving Transformations

While functors map objects and morphisms between categories, they can be understood as structure-preserving mappings that maintain the relational structure between objects.

Because a functor preserves identity and composition, the algebraic relationships between objects remain intact:

In functional programming, when you call list.map(f) or option.map(f), you are applying the functor’s morphism-mapping rule: lifting a basic transformation f:A→Bf : A \to B into F(f):F(A)→F(B)F(f) : F(A) \to F(B).

Let’s do the same job for a whole list of prices.

Suppose each item is being sent separately. We want to turn its price from pounds into pence, then add the same delivery charge in pence. For a £2 item with 50p delivery, that means 200p, then 250p.

We could convert every price on the list first, then go down the list adding delivery. Or we could do both steps for the first item, then both for the next, and so on. With the same exact arithmetic, we get the same answers in the same order.

That’s the promise behind mapping a rule over a list. We can reuse the steps we already understand, and joining those steps together still works as we’d expect.

2. Natural Transformations: Translating Between Perspectives

If a functor is a shift in perspective, what is a Natural Transformation?

Imagine you have two different perspectives on the same universe:

Can we construct a bridge that translates from perspective FF to perspective GG without disturbing the underlying domain transformations?

Definition: Given two functors F,G:𝒞→𝒟F, G : \mathcal{C} \to \mathcal{D}, a Natural Transformation α:F⇒G\alpha : F \Rightarrow G is a family of morphisms in 𝒟\mathcal{D} that assigns to every object A∈𝒞A \in \mathcal{C} a morphism: αA:F(A)→G(A)\alpha_A : F(A) \to G(A) such that for every morphism f:A→Bf : A \to B in 𝒞\mathcal{C}, the following diagram commutes: G(f)∘αA=αB∘F(f)G(f) \circ \alpha_A = \alpha_B \circ F(f)

graph LR
    FA["F(A) (e.g. Option A)"] -->|"α_A"| GA["G(A) (e.g. List A)"]
    FA -->|"F(f)"| FB["F(B) (e.g. Option B)"]
    GA -->|"G(f)"| GB["G(B) (e.g. List B)"]
    FB -->|"α_B"| GB

The Meaning of the Naturality Square

Look closely at the commutative square. It states that there are two ways to navigate from F(A)F(A) to G(B)G(B):

  1. Path 1: Transform within perspective FF first (F(f)F(f)), then translate to perspective GG (αB\alpha_B).
  2. Path 2: Translate to perspective GG first (αA\alpha_A), then transform within perspective GG (G(f)G(f)).

Naturality requires that both paths yield the exact same result:

αB(F(f)(x))=G(f)(αA(x))\alpha_B(F(f)(x)) = G(f)(\alpha_A(x))

A transformation is “natural” precisely because it is indifferent to the specific contents or operations happening inside the objects. It operates purely on the perspective wrapper itself.

Let’s write a couple of names on separate slips of paper.

We have Ada, then Sam. Put each slip in its own envelope and keep the envelopes in that order. Now suppose we want the names in capitals. We could have written them in capitals before putting them in, or we could open each envelope and change the name afterwards. We end up with the same thing.

Putting each name in its own envelope doesn’t depend on what the name says. We could change the names to their lengths instead, and the two orders would still agree. That’s the sort of agreement the square above asks for.

If we sorted names into envelopes according to their first letter, that would be a different job. Changing a name first could change which envelope it goes into. So we do have to check the promise, not assume every way of organising things will keep it.

3. Natural Transformations in Software

In strongly-typed functional programming, generic functions with the signature forall a. F a -> G a that operate uniformly on a are natural transformations (by Wadler’s “Theorems for Free”).

Example 1: option_to_list

Translating the perspective of uncertainty into multiplicity:

pub fn option_to_list(opt: Option(a)) -> List(a) {
  case opt {
    Some(val) -> [val]
    None -> []
  }
}

Naturality guarantees: list.map(f,option_to_list(opt))≡option_to_list(option.map(f,opt))\text{list.map}(f, \text{option\_to\_list}(opt)) \equiv \text{option\_to\_list}(\text{option.map}(f, opt))

Whether you map the function over the Option and then convert it to a List, or convert the Option to a List and then map the function, the final list is identical.

You know that second address line you sometimes leave blank?

Suppose we’re copying an address from a form onto a label. If there’s a second line, we put it on our list of lines to print. If it’s missing, we don’t add a line for it.

Now let’s say we also want every letter in capitals. We can do that on the form before copying, or on the copied line afterwards. Same address, same result. If the line is missing, neither way invents one.

That’s what the equation is checking. The copying rule only asks whether there’s a line to copy. It doesn’t need to know whose address it is, or how we’re changing the lettering.

Example 2: Container Reordering and Extraction

// Natural transformation: reversing a list preserves mapped transformations
pub fn check_naturality(items: List(a), f: fn(a) -> b) -> Bool {
  let path1 = list.map(list.reverse(items), f)
  let path2 = list.reverse(list.map(items, f))
  path1 == path2 // Always True!
}

Let’s turn a playlist round.

Suppose you’ve written down three songs and you want to play them in the opposite order. You also want a list of how long they last. Does it matter whether you reverse the songs first and then write down their lengths, or write down the lengths first and reverse those?

No: the lengths end up in the same order. Reversing doesn’t need to know anything about a song; it just moves the entries.

But sorting alphabetically would be another matter. Once we’ve replaced the songs with their lengths, the titles are gone. We can’t sort by something we no longer have. That’s a useful way to spot why one arrangement keeps the promise and another doesn’t.

4. Higher Dimensions: 3-Cells, 4-Cells, and Infinity

Before we go any higher, let’s get our bearings.

We’ve connected things, looked at them in different ways, and compared those ways of looking. Now comes a slightly cheeky question: could we compare the comparisons as well?

That’s the question behind the next bit. When I say “higher dimensions”, you don’t need to picture a four-dimensional room. Think of going up another level in what we’re talking about.

I like to do that by redrawing the diagram. Take something we were just studying, draw a box around it, then leave out the details inside. Now I can look at how that whole thing connects to others. The details haven’t vanished; I’ve just put them out of sight for a moment, as we did with the elements inside a set.

That picture helps me, but drawing another box doesn’t prove that the maths works. These extra layers need rules of their own. What follows is a first look at them, not another list of things you must learn before any of the earlier ideas are useful.

Notice the geometric dimension ladder we have climbed:

Dimension Categorical Cell What it Connects Geometric Intuition
0-cell Object (A,BA, B) Discrete points 0D Vertices
1-cell Morphism / Functor (f,Ff, F) 0-cells 1D Directed lines
2-cell Natural Transformation (α\alpha) 1-cells (Functors) 2D Surfaces between lines

Can this ladder continue? What is a morphism between 2-cells?

graph TD
    subgraph Functors ["1-Cells (Functors)"]
        F["F"]
        G["G"]
    end
    subgraph NatTrans ["2-Cells (Natural Transformations)"]
        alpha["α : F ⇒ G"]
        beta["β : F ⇒ G"]
    end
    alpha ==>|"Γ (3-Cell: Modification)"| beta

3-Cells: Modifications

An arrow connecting two natural transformations α,β:F⇒G\alpha, \beta : F \Rightarrow G is called a modification (a 3-cell). It assigns to every object AA a morphism in the target category that transforms the component αA\alpha_A into βA\beta_A while maintaining geometric consistency across the surface.

If a 2-cell is a surface stretching between two lines, a 3-cell is a volume filling the space between two surfaces.

Let’s try picturing this with a rubber band.

Stretch one between two fixed pins. You can pull the middle to one side and let it move into another shape without moving the ends. Now imagine two different ways of making that same change.

First we were talking about shapes. Then we were talking about movements between shapes. Now we’re asking how two of those movements compare. That’s the extra level I want you to picture.

The rubber band isn’t a definition of the new word above. It just gives us something to imagine while we sort out which level we’re talking about. The extra comparisons only make mathematical sense once we’ve supplied the rules for them.

4-Cells and Beyond: Coherences

In an ordinary 1-category, composition is strictly associative: (h∘g)∘f=h∘(g∘f)(h \circ g) \circ f = h \circ (g \circ f). In higher categories, transformations are often isomorphic up to a higher cell rather than strictly identical:

  1. Functor composition is associative only up to a 2-cell (the associator).
  2. Different ways to re-parenthesize four composed functors produce five groupings, forming the Stasheff pentagon. For this pentagon to commute, the equations must hold up to a 3-cell.
  3. The relationships between 3-cells are governed by 4-cells, and so on.

These higher cells are called coherences. They ensure that as you navigate higher-dimensional paths, equations remain consistent.

Do the different ways round actually agree?

Suppose you’ve written an appointment on a paper calendar and you’re copying it into your phone. You could copy it straight across, or copy it into a diary first and then into your phone. You’d want the date and time to agree either way.

That’s an everyday reason to care about different routes giving consistent answers. The maths here carries that concern further: when we use comparisons to relate the routes, those comparisons need to agree with one another too.

Copying a diary isn’t itself an example of all these higher layers. It’s a way to keep the underlying question in view: have we made sure that all these ways of getting from here to there fit together?

The ∞\infty-Category

Extending this structure inductively yields ∞\infty-categories (higher category theory) and Homotopy Type Theory (HoTT):

In modern computational type theory, equality between types is formulated as a space of paths. Reasoning across higher cells means reasoning about equivalences between equivalences, providing the mathematical foundation for formal proof verification and compiler semantics.

Let’s pause before the infinity sign makes this sound bigger than it needs to.

Imagine two walks from your front door to the same shop. On an open patch of ground, you might gradually shift one route across until it follows the other, keeping the start and finish fixed. Put a lake between the routes, and you might not be able to do that without crossing the water.

That gives us a picture of comparing paths, rather than just asking where they end. We can then ask about different ways of making that comparison, and keep asking the next question. The infinity sign lets us talk about a setting with no fixed last level; it isn’t asking us to draw every level.

These are pictures to help us find our way, not the full definitions, and the earlier maths doesn’t automatically include all these layers. If you’ve kept hold of why the missing address line stays missing whichever order we do the work in, you’ve already taken something useful from this part.

Summary

This series outlined the progression from set-theoretic foundations to higher category theory:

  1. Part 1: Collections and Arrows: Focused on directed, composable transformations and associativity rather than element inspection.
  2. Part 2: Isomorphism and Structural Sameness: Defined structural equality through invertible transformations (isomorphisms).
  3. Part 3: Universal Constructions and Duality: Characterized products and sums via universal properties and categorical duality.
  4. Part 4: The External Universe and Category Axioms: Defined elements, singletons, and initial/terminal objects externally via Lawvere’s ETCS and formulated the category axioms.
  5. Part 5: Functors and Natural Transformations: Analyzed structure-preserving mappings between categories and uniform translations between functors.

Previous: Part 4: The External Universe and Category Axioms