Chapter 2: Type Systems and Polymorphism
Every working programmer has fought a type checker, and most have wondered whether the fight was worth it. This chapter answers that question by treating a type system for what it is: a lightweight formal method, a decidable and purely syntactic proof system that rejects a whole class of programs before they run. Its correctness guarantee has a precise name, soundness, and a precise statement: soundness is progress plus preservation, or in the slogan, “well-typed programs don’t get stuck.” Nearly everything else in the area, from generics to variance annotations, is engineering built around that one theorem.
Concepts from other sections (9)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- Variance: how subtyping on a type argument lifts to the constructed type: covariant, contravariant, or invariant. Read more: 2.4 Generics at runtime and language comparison
- Ad-hoc polymorphism: a different implementation per type, chosen by the types involved (overloading, typeclasses, traits, interfaces). Read more: 2.4 Generics at runtime and language comparison
- Typing judgment: the statement , that expression has type in context . Read more: 2.4 Generics at runtime and language comparison
- Occurs check: the test that a type variable does not appear inside the type it is being bound to, which keeps types finite. Read more: 2.4 Generics at runtime and language comparison
- Partial order: a relation that is reflexive, antisymmetric ( and imply ), and transitive, such as or “is a subset of”; some pairs may be incomparable, which is why dependency graphs need a topological sort. Read more: Chapter 11: Discrete Math 1 in Mathematics
- Monomorphization: compiling generics by emitting a specialized copy per concrete type. Read more: 2.4 Generics at runtime and language comparison
- Principal type: the most general type of a term, of which all its other types are instances. Read more: 2.4 Generics at runtime and language comparison
- Gradual typing: a type system in which static type annotations are optional and unannotated code stays dynamically typed; Python’s interpreter ignores annotations, and checkers such as mypy and pyright enforce them. Read more: Chapter 22: Python
- Vtable: a table of function pointers used for dynamic dispatch, here written by hand. Read more: 19.7 Function: type erasure with a small buffer
The second thread of the chapter is polymorphism, the machinery that buys back expressiveness without giving up the guarantee. “Polymorphism” turns out to be one word for four different mechanisms, and much of the confusion in “generics versus interfaces” arguments dissolves once you can name which one you mean. You will follow the classic lambda-calculus ladder from the simply typed calculus to System F, then see why full polymorphic inference is undecidable and how Hindley–Milner carves out the decidable slice that OCaml, Haskell, Elm, and the local inference in Rust, Swift, and TypeScript all descend from. From there the chapter turns practical: how ad-hoc polymorphism dispatches in Haskell, Rust, and Go; why List<Dog> is not automatically a List<Animal>; and why the same generic function has three different runtime stories depending on how a language compiles it.
The chapter is anchored by runnable code. code/hindley_milner.py is the whole of Algorithm W in about 250 lines, and five companion programs in OCaml, TypeScript, Go, Rust, and Haskell walk the same running example (a Shape with area, a generic Stack<T>, and a largest/Max over ordered things) through type systems that make different choices. Running them side by side is the clearest way to see that the concept stays fixed while the mechanism changes.
Learning objectives
- Read typing judgments and inference rules, and state soundness as progress plus preservation.
- Classify a piece of polymorphic code as parametric, ad-hoc, subtype, coercion, or bounded, and say which mechanism a given language feature uses.
- Explain how Hindley–Milner inference works (unification, the occurs check, instantiation, and
let-generalization) and trace it on small terms.- Derive the variance of a type constructor, including the contravariant rule for function arguments, and explain the soundness holes that real languages accept.
- Predict the runtime cost of generics in a language from whether it monomorphizes, erases, or passes dictionaries.
Before you begin
Section titled “Before you begin”The chapter assumes the proof techniques from Discrete Math 1 in Mathematics: proofs, induction, and relations (the subtype relation <: is a partial order). Comfort reading inference rules helps, but the notation is taught here. You will get the most out of the code if you have already written some Python, C, Rust, and Go, so the five-language comparison lands on familiar ground.
In this chapter
Section titled “In this chapter”- Soundness and polymorphism: Relate progress and preservation to kinds of polymorphism.
- System F and type inference: Trace generalization, instantiation, and the occurs check.
- Dispatch, variance, and type expressiveness: Distinguish bounded dispatch from subtyping and derive variance.
- Generics at runtime and language comparison: Connect monomorphization, erasure, and dictionary passing to runtime behavior.
Companion code
Section titled “Companion code”code/hindley_milner.py: Algorithm W end to end. It infers principal types for\x.x,\f.\g.\x. f (g x), andlet id = \x.x in id idwith no annotations, then shows the occurs check rejecting\x. x x.code/inference.ml: OCaml inferring the exact same principal types from the user’s side.code/polymorphism.ts: structural, gradual typing with type-level computation (DeepReadonly) and explicit variance.code/generics.go: Go’s type-set constraint model and GC-shape stenciling.code/traits.rs: nominal traits and the split between static (<T: Trait>, monomorphized) and dynamic (dyn Trait, vtable) dispatch.code/typeclasses.hs: typeclasses as dictionary passing, plus the higher-kindedFunctor.
A good way to work is to run the keystone first: read unify, instantiate, and generalize in hindley_milner.py, because that triple is ML type inference, and then open inference.ml to watch a production compiler reach the same answers. After that, run the four language files side by side. All of them print the same shape of output (areas, a Stack, a largest).