Higher-order category

Structure of structures, scalable software patterns

Published:
 _   _ ___ ____ _   _ _____ ____        ___  ____  ____  _____ ____  
| | | |_ _/ ___| | | | ____|  _ \      / _ \|  _ \|  _ \| ____|  _ \ 
| |_| || | |  _| |_| |  _| | |_) |____| | | | |_) | | | |  _| | |_) |
|  _  || | |_| |  _  | |___|  _ <_____| |_| |  _ <| |_| | |___|  _ < 
|_|_|_|___\____|_| |_|_____|_| \_\     \___/|_|_\_\____/|_____|_| \_\
  ____    _  _____ _____ ____  ___  ____  ___ _____ ____  
 / ___|  / \|_   _| ____/ ___|/ _ \|  _ \|_ _| ____/ ___| 
| |     / _ \ | | |  _|| |  _| | | | |_) || ||  _| \___ \ 
| |___ / ___ \| | | |__| |_| | |_| |  _ < | || |___ ___) |
 \____/_/   \_\_| |_____\____|\___/|_| \_\___|_____|____/ 

Remember the functor country-road example? A functor essentially gives us a way to navigate from one country to another by providing a comfortable vehicle. But what about traveling from one country to another on a different planet? No vehicle can handle such a task. To reach a different dimension, we have to build a new, interplanetary one. Regular categories help us navigate a 2D world. A 3D world requires a different approach.

If categories are like a city with buildings (objects) connected by roads (morphisms), then higher-order categories are like a multi-level metropolis with highways, overpasses, and those confusing interchange ramps that somehow connect to each other in ways that make perfect sense once you understand the master plan (and absolutely no sense until you do). They also have spaceship stations for interplanetary, intergalactic, and interstellar travel.

In regular category theory, we have objects and arrows between them. But what happens when you want arrows between your arrows? What if you need to transform your transformations? What if your morphisms themselves need morphisms? That's when you realize you've outgrown regular categories and need to level up to the big leagues.

Higher-order categories give us the vocabulary to talk about structures within structures within structures. They're the reason why certain advanced Haskell libraries seem to have an almost impossible composability.

This is where category theory stops being cute and starts being genuinely powerful. We're about to explore the mathematical machinery that makes the impossible possible and the complex simple.

Formal definition #

In category theory, morphisms can be classified by the dimensionality of the data they operate on. The simplest morphisms are those that we originally introduced. They operate directly on the category's objects. But since morphisms do not really care about the nature of the objects they operate with, we can construct a category where the objects are morphisms from the initial category (Arrow category is just one example). This process can be repeated, creating groups of morphisms of increasing order. To make sense of the variety, we tag each group with a number.

k-morphisms #

Groups of morphisms, parameterized by a natural number representing their dimensionality, are called k-morphisms[4] or k-cells.

  • 0-morphism is an object
  • 1-morphism is a morphism—an arrow between two objects
  • 2-morphism is a k-morphism for k = 2, a higher morphism between ordinary 1-morphisms
  • and so on
2-morphism cell shapes

1. Globular (two parallel 1-morphisms between the same objects)

         f
      ╭────→╮
     a   ⇓   b
      ╰────→╯
         g

2. Simplicial (2-simplex filling a triangle)

         b
      ↗  ⇓  ↘
    a -------> c

3. Cubical (2-cube filling a square)

        b
     ↗    ↘
    a   ⇓   d
     ↘    ↗
        c

Higher-order category #

A higher-order category[1][2] is a categorical structure that extends beyond the basic notion of objects and morphisms by introducing additional levels of morphisms between morphisms. It's a generalization of category theory to a context where there are not only morphisms between objects, but generally k-morphisms between (k − 1)-morphisms for all k ≥ 1 (with 0-morphisms as objects).

A higher-order category has to satisfy the following laws:

  1. Composition Laws:

    • k-morphisms compose vertically with other k-morphisms
    • Horizontal composition involves specific categorical structures between adjacent levels
    • Composition must be associative at each level (either strictly or up to coherent isomorphism)
  2. Identity Laws:

    • Each k-morphism has an identity k-morphism (at the same level)
    • Each level has appropriate identity morphisms that act as neutral elements
    • Left and right unit laws: id ∘ f = f = f ∘ id (at each level)
  3. Interchange Laws:

    • Different types of composition must be compatible
    • For 2-morphisms (using ∘ for vertical composition and ⊙ for horizontal composition): (β₂ ∘ β₁) ⊙ (α₂ ∘ α₁) = (β₂ ⊙ α₂) ∘ (β₁ ⊙ α₁)
    • Higher dimensions require more complex interchange conditions
  4. Coherence Conditions:

    When laws hold "up to isomorphism" (weak case), these isomorphisms must satisfy coherence axioms[3]

    • Whiskering Operations:
      • Left whiskering f ▷ α: composing a 1-morphism f with a 2-morphism α on the left
      • Right whiskering α ◁ g: composing a 2-morphism α with a 1-morphism g on the right

    These operations allow 2-morphisms to interact with 1-morphisms in coherence laws.

    • Pentagon axiom for associativity: The Pentagon axiom (also called the Pentagon identity) is a fundamental coherence condition for 1-morphisms that ensures associativity isomorphisms behave consistently when reassociating compositions of four morphisms. Composition of 1-morphisms is associative only up to isomorphism. When we have four composable morphisms f, g, h, k, there are five ways to associate them:

      • ((k ∘ h) ∘ g) ∘ f
      • (k ∘ (h ∘ g)) ∘ f
      • (k ∘ h) ∘ (g ∘ f)
      • k ∘ ((h ∘ g) ∘ f)
      • k ∘ (h ∘ (g ∘ f))

      Each adjacent pair is connected by an associator isomorphism, and we need these paths to be coherent.

                ((k∘h)∘g)∘f ──── α(k,h,g) ◁ f ────→ (k∘(h∘g))∘f
                   ╱                                     ╲
        α(k∘h,g,f)╱                                       ╲α(k,h∘g,f)
                 ↙                                         ↘
            (k∘h)∘(g∘f)                               k∘((h∘g)∘f)
                 ╲                                         ╱
        α(k,h,g∘f)╲                                       ╱k ▷ α(h,g,f)
                   ↘                                     ↙
                              k∘(h∘(g∘f))
      

      For morphisms f: A → B, g: B → C, h: C → D, k: D → E, the pentagon axiom states:

      α(k,h,g∘f) ∘ α(k∘h,g,f) = (k ▷ α(h,g,f)) ∘ α(k,h∘g,f) ∘ (α(k,h,g) ◁ f)

      Where α(x,y,z) represents the associator isomorphism (x ∘ y) ∘ z ≅ x ∘ (y ∘ z), and ▷, ◁ are left and right whiskering operations.

      Without the pentagon axiom:

      • Multiple paths between the same compositions might not commute
      • Compositions would be ambiguous - different association orders could yield different results
      • Composition in higher-order structures wouldn't be well-defined
    • Triangle axiom for units: The Triangle axiom (also called the Triangle identity) is a coherence condition that governs the interaction between associator and unitor isomorphisms. When both associativity and unit laws hold only up to isomorphism, we need coherence conditions to ensure consistency when these interact.

      For morphisms f: A → B and g: B → C, there are two ways to transform (g ∘ id_B) ∘ f to g ∘ f:

      1. Apply the associator, then apply the left unitor on f via whiskering: (g ∘ id_B) ∘ f → g ∘ (id_B ∘ f) → g ∘ f
      2. Apply the whiskered right unitor on g directly: (g ∘ id_B) ∘ f → g ∘ f
              (g ∘ id_B) ∘ f
                   ╱     ╲
                  ╱       ╲
        α(g,id_B,f)        ρ_g ◁ f
                ╱           ╲
               ↙             ↘
          g ∘ (id_B ∘ f) ───→ g ∘ f
                      g ▷ λ_f
      

      For morphisms f: A → B and g: B → C, the triangle axiom states: (g ▷ λ_f) ∘ α(g, id_B, f) = ρ_g ◁ f

      Where:

      • λ_f: id_B ∘ f ≅ f (left unitor)
      • ρ_g: g ∘ id_B ≅ g (right unitor)
      • α(g, id_B, f): (g ∘ id_B) ∘ f ≅ g ∘ (id_B ∘ f) (associator)

      The triangle axiom ensures that:

      • Identity morphisms behave consistently with associativity
      • Unit laws interact properly with associativity laws
      • Simplifications are unique - there's only one canonical way to simplify expressions involving identities

      The triangle axiom guarantees that simplifying (g ∘ id_B) ∘ f directly via the right unitor ρ_g yields the same result as reassociating to g ∘ (id_B ∘ f) and simplifying via the left unitor λ_f.

    • Higher-dimensional coherence for n > 2

  5. Functoriality:

    • Composition operations are functorial in their arguments
    • Respects the categorical structure at each level

These laws ensure that higher-order categories have well-behaved compositional structure that generalizes ordinary category theory in a consistent way.

The most important examples are 2-categories and bicategories.

2-Category #

A 2-category[5] C consists of:

  1. 0-cells (objects): A, B, C, etc.
  2. 1-morphisms (morphisms): f: A → B, g: B → C, etc.
  3. 2-morphisms (morphisms between morphisms): α: f ⇒ g where f, g: A → B

Along with:

Composition Operations (subscripted by the shared boundary dimension):

  • Horizontal composition (∘₀): Composition along a 0-cell boundary
    • For 1-morphisms: g ∘₀ f: A → C when f: A → B and g: B → C (often written simply g ∘ f)
    • For 2-morphisms side-by-side: β ∘₀ α: g₁ ∘₀ f₁ ⇒ g₂ ∘₀ f₂ when α: f₁ ⇒ f₂ (with f₁, f₂: A → B) and β: g₁ ⇒ g₂ (with g₁, g₂: B → C)
  • Vertical composition (∘₁): Composition of 2-morphisms along a 1-morphism boundary
    • β ∘₁ α: f ⇒ h when α: f ⇒ g and β: g ⇒ h (with f, g, h: A → B)

Identity Elements:

  • Identity 1-morphisms: id_A: A → A for each 0-cell A
  • Identity 2-morphisms: id_f: f ⇒ f for each 1-morphism f

Coherence Laws:

  • Associativity for both horizontal and vertical composition
  • Unit laws for identity morphisms
  • Interchange law: (β₂ ∘₁ β₁) ∘₀ (α₂ ∘₁ α₁) = (β₂ ∘₀ α₂) ∘₁ (β₁ ∘₀ α₁)

2-categories are strict: all laws hold as equalities, so composition is strictly associative.

Bicategory #

A bicategory is like a 2-category, but with relaxed associativity and unit laws. For composable 1-morphisms f: A → B, g: B → C, and h: C → D, instead of strict equality we have:

  1. Associativity up to isomorphism:

    • α_{h,g,f}: (h ∘₀ g) ∘₀ f ≅ h ∘₀ (g ∘₀ f) (associator - an invertible 2-morphism)
  2. Unit laws up to isomorphism:

    • λ_f: id_B ∘₀ f ≅ f (left unitor - an invertible 2-morphism)
    • ρ_f: f ∘₀ id_A ≅ f (right unitor - an invertible 2-morphism)

Coherence Conditions:

  • Pentagon identity for associators
  • Triangle identity for unitors (compatibility between associators and unitors)

Bicategories are weak: laws hold up to coherent isomorphism, which is more flexible but requires explicit coherence data.

Higher Dimensions #

The pattern continues:

  • 3-categories: Add 3-morphisms between 2-morphisms
  • n-categories: Add morphisms at every level up to n
  • ∞-categories: Infinite tower of higher morphisms

Key Examples #

Pullback - Fiber Product #

    X -- f --> Z <--- g --- Y

The pullback of f and g is a set X ×_Z Y together with projection functions that make this diagram commute:

    X ×_Z Y --- π₂ --> Y
      |                |
    π₁|                |g
      |                |
      ↓                ↓
      X ----- f -----> Z

Where X ×_Z Y = {(x,y) ∈ X × Y | f(x) = g(y)} and:

  • π₁(x,y) = x
  • π₂(x,y) = y
  • f(π₁(x,y)) = g(π₂(x,y)) (commuting condition)

The pullback has the universal property: for any other set W with functions h₁: W → X and h₂: W → Y such that f ∘ h₁ = g ∘ h₂, there exists a unique function h: W → X ×_Z Y making the diagram commute (π₁ ∘ h = h₁ and π₂ ∘ h = h₂).

Cat (2-category) #

The category of categories, denoted Cat, is a 2-category where:

  • Objects (0-cells): Small categories themselves (conceptually similar to familiar examples like Set, Group, Top, or the idealized Hask, setting size subtleties aside)
  • Morphisms (1-morphisms): Functors between categories
  • 2-morphisms: Natural transformations
  • Composition: Composition of functors (horizontal) and natural transformations (vertical and horizontal)
  • Identity: Identity functors for each category and identity natural transformations for each functor

In Cat, a morphism F: C → D is a functor that preserves the structure of category C when mapping to category D. This meta-level perspective allows us to study categories as mathematical objects in their own right.

Span (bicategory) #

The bicategory Span provides an example of a bicategory that's not a 2-category:

  • 0-cells: Sets
  • 1-morphisms: Spans of sets
  • 2-morphisms: Span morphisms

A span from set A to set B is a diagram:

    S
   ↙ ↘
  A   B

Where S is some set with functions to both A and B.

Composition of spans: Given spans A ← S → B and B ← T → C, their composite is:

      S ×_B T
     ↙       ↘
    A          C

Where S ×_B T is the pullback (fiber product) over B.

Why it's a bicategory, not a 2-category:

  • Both associativity and unit laws hold only up to canonical isomorphism
  • For a third span C ← U → D, the pullback (S ×_B T) ×_C U is naturally isomorphic to S ×_B (T ×_C U), and composing with the identity span B ← B → B gives S ×_B B ≅ S, but neither is a strict equality
  • This requires associator and unitor isomorphisms that satisfy the pentagon and triangle axioms

A 2-morphism between spans A ← S₁ → C and A ← S₂ → C is a function f: S₁ → S₂ that makes both triangles commute:

        S₁
      ╱ │ ╲
     ╱  f  ╲
    ↙   ↓   ↘
   A ←─ S₂ ─→ C

This bicategory is fundamental in:

  • Database theory: Spans model relations and their joins
  • Concurrency theory: Spans represent processes and their synchronization
  • A 2-category is like a bicategory where associativity and units hold on the nose (strictly).
  • A bicategory is the weaker version where associativity/unit laws hold only up to coherent isomorphism.

Van Laarhoven Encoding #

A particular application of higher-order categorical thinking in functional programming is the Van Laarhoven encoding[7] pattern. This encoding demonstrates how rank-2 polymorphism and functor abstraction can create powerful, composable abstractions.

The Van Laarhoven Pattern #

The Van Laarhoven encoding represents certain data access patterns as polymorphic functions over arbitrary functors:

type VanLaarhoven s a = forall f. Functor f => (a -> f a) -> s -> f s

This type signature encodes a constraint: given any functor f and a way to transform the "focus" a into f a, we can transform the entire structure s into f s. The universality (forall f) is key—it means the implementation must work for any functor, which severely constrains what the function can actually do.

Parametricity and Constraint #

By parametricity[6], a function of type VanLaarhoven s a can only:

  1. Extract some a from the s
  2. Apply the given transformation a -> f a to get an f a
  3. Reconstruct an f s that represents the structure with the focused part transformed

The function cannot inspect the functor f or the specific transformation being applied—it must work uniformly for all possible functors.

Composition and Categorical Structure #

Van Laarhoven encodings compose naturally due to their functorial structure:

-- Composition of Van Laarhoven encodings
composeVL :: VanLaarhoven b c -> VanLaarhoven a b -> VanLaarhoven a c
composeVL bc ab = \f -> ab (bc f)

-- Identity
idVL :: VanLaarhoven a a  
idVL f = f

-- Example: nested structure access
data Company = Company { lead :: Person }
data Person = Person { address :: Address }
data Address = Address { street :: String }

-- Individual accessors
leadVL :: VanLaarhoven Company Person
addressVL :: VanLaarhoven Person Address
streetVL :: VanLaarhoven Address String

-- Composed accessor: company -> lead's street
leadStreetVL :: VanLaarhoven Company String
leadStreetVL = composeVL streetVL
             . composeVL addressVL
             $ leadVL

The Van Laarhoven encoding exemplifies several higher-order categorical principles:

  1. Functor Abstraction: The pattern works by abstracting over the choice of functor, using only the functorial structure (fmap).

  2. Parametricity: Instantiating with any functor f yields components that vary functorially (parametricity forces them to respect f's action in a uniform way).

  3. Parametricity as Constraint: The universal quantification forall f. Functor f => drastically restricts admissible implementations to "extract + rebuild" shaped behaviors.

  4. Compositional Structure: Van Laarhoven encodings themselves form a category where:

    • Objects are types
    • Morphisms are Van Laarhoven encodings between those types
    • Composition is plain function composition
    • Identity is the polymorphic identity function

This pattern shows how higher categorical and parametric principles (functors, naturality, and polymorphic constraints) yield powerful abstractions: expressiveness via disciplined restriction.

Visualizing higher-order categories #

1. k-morphisms hierarchy:

0-morphisms (objects): A, B, C
1-morphisms (arrows): f, h: A -> B and g, k: B -> C
2-morphisms (arrows between arrows): α, δ: f ⇒ h and β: g ⇒ k
3-morphisms (arrows between 2-morphisms): Γ: α ⟹ δ

Level 0: Objects
A     B     C

Level 1: Morphisms between objects
A ---f---> B ---g---> C

Level 2: Morphisms between morphisms
A ---f---> B ---g---> C
    α ⇓        β ⇓
A ---h---> B ---k---> C

Level 3: Morphisms between 2-morphisms
       f
   ╭──────→╮
A  α ═Γ⟹ δ  B
   ╰──────→╯
       h


2. 2-Category structure:

Objects: A, B, C
1-morphisms: f, h, j: A -> B and g, k: B -> C
2-morphisms: α: f ⇒ h, γ: h ⇒ j, and β: g ⇒ k

Horizontal composition (∘₀):
A ---f---> B ---g---> C    
    α ⇓       β ⇓         
A ---h---> B ---k---> C    

Result: (β ∘₀ α): (g ∘₀ f) ⇒ (k ∘₀ h)

Vertical composition (∘₁):
A ---f---> B
    α ⇓      
A ---h---> B
    γ ⇓      
A ---j---> B

Result: (γ ∘₁ α): f ⇒ j


3. Pentagon axiom:

Four morphisms: A -f-> B -g-> C -h-> D -k-> E

          ((k∘h)∘g)∘f ──── α(k,h,g) ◁ f ────→ (k∘(h∘g))∘f
             ╱                                     ╲
  α(k∘h,g,f)╱                                       ╲α(k,h∘g,f)
           ↙                                         ↘
      (k∘h)∘(g∘f)                               k∘((h∘g)∘f)
           ╲                                         ╱
  α(k,h,g∘f)╲                                       ╱k ▷ α(h,g,f)
             ↘                                     ↙
                        k∘(h∘(g∘f))

Both paths from ((k∘h)∘g)∘f to k∘(h∘(g∘f)) must commute for coherent associativity.


4. Triangle axiom:

Identity and composition: A -f-> B -id_B-> B -g-> C

  (g ∘ id_B) ∘ f ──── ρ_g ◁ f ────→ g ∘ f
        │                             ↑
        │                             │
  α(g,id_B,f)                      g ▷ λ_f
        │                             │
        ↓                             │
  g ∘ (id_B ∘ f) ─────────────────────┘

Both paths from (g ∘ id_B) ∘ f to g ∘ f must be equal.


5. Bicategory vs 2-category:

2-category (strict):

A ---f---> B ---g---> C ---h---> D
(h∘g)∘f = h∘(g∘f)  ✓ (strict equality)

Bicategory (weak):  

A ---f---> B ---g---> C ---h---> D
(h∘g)∘f ≅ h∘(g∘f)  ✓ (isomorphism)
     ↕ α(h,g,f)


6. Span bicategory:

Objects: Sets X, Y, Z

1-morphism (span from X to Y):
      S
     ↙ ↘
    X   Y

Composition of spans X <- S -> Y and Y <- T -> Z:
      S ×_Y T
     ↙       ↘
    X         Z

2-morphism between spans X <- S₁ -> Y and X <- S₂ -> Y:
        S₁
      ╱ │ ╲
     ╱  φ  ╲
    ↙   ↓   ↘
   X ←─ S₂ ─→ Y

Where φ makes both triangles commute.


7. Cat 2-category:

0-cells: Categories C, D, E
1-morphisms: Functors F, H, K: C -> D and G: D -> E
2-morphisms: Natural transformations α: F ⇒ H and β: H ⇒ K

    C ---F---> D ---G---> E
        α ⇓       
    C ---H---> D        

Natural transformation α has components:
α_X: F(X) -> H(X) for each object X in C

Functor composition: G ∘₀ F: C -> E
Natural transformation composition: β ∘₁ α: F ⇒ K

Conclusion #

Higher-order categories extend the foundational ideas of category theory to new dimensions, allowing us to reason about morphisms between morphisms, and even higher levels of structure. By introducing k-morphisms, coherence laws, and examples like 2-categories and bicategories, we gain powerful tools for modeling complex systems in mathematics, computer science, and beyond.

These structures unify and generalize familiar concepts such as composition, identity, and associativity, but at every level of abstraction. The coherence conditions (pentagon and triangle axioms) ensure that all ways of composing morphisms are consistent, making higher-order categories a robust framework for advanced reasoning.

Source code #

Reference implementation (opens in a new tab)

References

  1. Higher category theory (Wikipedia) (opens in a new tab) · Back
  2. Higher category theory (nLab) (opens in a new tab) · Back
  3. Coherence law (opens in a new tab) · Back
  4. k-morphism (opens in a new tab) · Back
  5. 2-category (opens in a new tab) · Back
  6. Parametricity (opens in a new tab) · Back
  7. CPS based functional references (Twan van Laarhoven) (opens in a new tab) · Back