Act III · Speaking to the Machine
Part 14 of 61Lambda and Types
How much of a programming language is left when everything but functions is taken away?
The part opens with the Job written in a lambda core with not one type annotation, and with every type inferred, and beneath it two plus three written with functions alone and rewritten by one rule to the numeral five in six steps. Church's calculus has three kinds of term and one computation rule, beta-reduction, which needs capture-avoiding substitution to be right. Booleans, numerals, pairs, Kleene's predecessor and, through the Y combinator, recursion are all encoded and counted in beta-steps: four factorial takes 10,384 of them. Strategies differ in whether they find a normal form, and Church-Rosser says they cannot disagree about which one, which the part checks on the whole reduction graph of a term. Then types: the simply typed calculus rejects stuck terms, progress and preservation are proved and run on 5,000 random terms, and the typed core always terminates, which is why Omega has no type. Hindley-Milner infers principal types by unification, System F adds polymorphism and free theorems, and under Curry-Howard a type is a proposition and a program is its proof. The part ends at dependent, linear and gradual types, with rustc and tsc on this machine supplying the error messages.
What you need. Functions as values in any programming language, and proof by induction. Part 1's lambda calculus is recalled, not assumed.
- Mathematics, ideas and history
- λ-calculus, Church encodings, Y, Church–Rosser, STLC, progress and preservation, Hindley–Milner, System F, Curry–Howard, linear types
- What we build or compute
- a λ reducer; type inference
What you will be able to do
Degree
- Reduce a lambda term by hand with capture-avoiding substitution, and say whether it has a normal form.
- Write Church booleans and numerals and compute plus, times and the predecessor on them.
- Type a small term in the simply typed lambda calculus by drawing its derivation tree.
Graduate
- Prove progress and preservation for the simply typed calculus, naming the canonical-forms and substitution lemmas.
- Run Algorithm W on a let-polymorphic program, with unification and the occurs check.
- Translate a propositional formula into a type and find a term for it, or a Kripke countermodel.
Research
- Sketch Tait's proof of strong normalization by logical relations and say why adding fix ends it.
- State a research question about gradual typing, polymorphic inference or cubical computation with its model made explicit: the cast semantics, the cost model and the baseline.
Industry
- Explain why TypeScript accepts a covariant array write that fails at run time, and what a sound gradual type system would charge for it.
- Read rustc's ownership and borrowing errors as a linear and affine type discipline at work.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Degree 17 min · Graduate 47 min · Research 51 min · Industry 21 min.
- 0A language made of functionsDegree2 min
- 1Terms, variables and substitutionDegree3 min
- 2Reduction and normal formsDegree3 min
- 3Programming with nothingDegree4 min
- 4Recursion without namesGraduate2 min
- 5Evaluation strategiesGraduate3 min
- 6Church–Rosser, and de BruijnGraduate2 min
- 7Simple typesDegree4 min
- 8Well-typed programs cannot go wrongGraduate3 min
- 9Why the typed core terminatesGraduate3 min
- 10Hindley–Milner inferenceGraduate4 min
- 11Polymorphism and free theoremsGraduate3 min
- 12Propositions as typesGraduate4 min
- 13Dependent and linear typesGraduate3 min
- 14Data, subtyping and gradual typesIndustry4 min
- 15Frontier: the edges of type theoryResearch4 min
- Recap, problems, and where this comes backAll tracks2 min
Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · 中文 · Build the film.
Lecture
The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film.
A language made of functionsDegree2 min
Here is the Job once more, written in a new language: the lambda core, which this part builds. It has functions, lists and pairs, and nothing else worth mentioning. Notice what is missing. There is not one type annotation. bump adds one to a word's count in the table, count runs over all the words, and job puts the pieces together. Yet the compiler knows the type of every function. It worked them out by itself, in a few hundred tiny steps. And some of these types contain a variable, written tick a. bump works for words, but it would work just as well for numbers, or for anything that can be compared for equality. The machine discovered that too.
And underneath the lambda core there is something even smaller. Here is two plus three, written with functions and nothing else: no numbers, no addition, only functions applied to functions. One rule, applied again and again, rewrites it, until it stops. And the result is the number five, or rather, a function that applies f to x five times. Alonzo Church found in the nineteen thirties that this one rule is enough to compute anything that can be computed. Part 1 met his lambda calculus; this part takes it seriously.
Here is the route through the lesson. Build numbers, booleans, lists and recursion from functions in the pure untyped calculus. Compare full reduction with weak evaluation: strategies can differ in termination and cost, while beta normal forms remain unique when they exist. Add a specific simple type system and prove progress and preservation for its closed programs. Infer principal types in a small ML core, then examine which richer features change those guarantees. Finally, read types as propositions and terms as evidence in a stated logical calculus. Keeping the model visible lets these connections explain one another without promising the same theorem for every programming language.
1Terms, variables and substitutionDegree3 min
The untyped lambda calculus has three term constructors. A variable; an abstraction, lambda x dot t, binding x in its body; and an application, one term applied to another. Read the example's parentheses carefully. The left function is lambda x, x x. Its single argument is the whole application of lambda y, y to z. The syntax tree makes that grouping explicit, with at signs for applications. Application normally associates to the left: f a b means the result of f a applied to b. A lambda body extends rightward until a closing delimiter. Parentheses override those conventions. The tree, rather than an ambiguous spoken string, determines what substitution will copy.
Variables come in two kinds. In lambda x, f x y, the x is bound: it refers to the lambda that introduced it, like a function's parameter. f and y are free. They refer to something outside the term, and the term's meaning depends on what they turn out to be. A bound variable's name does not matter. Lambda x, x and lambda y, y are the same function, the identity, and terms that differ only in bound names are called alpha equivalent, just as the integral of f of x d x is the integral of f of t d t.
Computation in the lambda calculus is substitution: to apply a function, replace its parameter by the argument. That is subtler than it looks. Take lambda x, lambda y, x: a function that takes two arguments and returns the first. Apply it to a free variable y. Replacing x by y naively gives lambda y, y: the identity function. The free y has been captured by the inner lambda, and the meaning has changed. The correct answer renames the bound y first, to y prime, and gives lambda y prime, y: still a function that ignores its argument and returns y. Capture-avoiding substitution is defined by these rules, and the last one carries the condition. Getting this right is the first bug every implementer of a programming language meets, and the reason closures exist, as Part 15 will show.
2Reduction and normal formsDegree3 min
The calculus computes with a single rule, called beta reduction. Wherever a lambda is applied to an argument, the pair is a redex, a reducible expression. Replace it by the function's body, with the argument substituted for the parameter. A redex can sit anywhere inside a larger term, even inside the body of another lambda, and any redex may be reduced at any time. Lambda x, x x applied to z becomes z z. That is all there is.
Here is a step on the tree. The whole term is a redex: lambda x, x x, applied to an argument that is itself a redex. Reducing the outer one substitutes the argument for both occurrences of x. The argument has been copied, and its redex with it: now there are two. Reduce the first copy, and one remains. This copying is the source of most of what follows: of the cost differences between strategies, and of the reasons a compiler shares work instead of repeating it.
Here is two plus three again, slowly. A numeral n is the function that applies f to x n times, and plus takes m and n and applies f m times on top of n applications. Each line reduces the redex shown in yellow. First plus swallows its arguments, one at a time. Then three is applied to f and x, and expands into three applications of f, and two adds two more on the outside. The last line has no redex left. It is a normal form: the answer, five applications of f.
Not every term has a normal form. Omega applies lambda x, x x to itself. One step of beta reduction gives back exactly the same term, and the next step the same again, forever. Omega has no normal form: it is the lambda calculus's infinite loop. Worse, some terms have a normal form along one path and loop along another. Here is a function that ignores its first argument, applied to omega and to z. Reduce the outside first and the answer is z, in two steps. Insist on reducing omega first, and you never finish. So the order of reduction matters. Chapter five studies it.
3Programming with nothingDegree4 min
If the language has nothing but functions, then data must be functions too. Church showed how. A boolean is a choice between two things. True takes two arguments and returns the first; false returns the second. Then if b then x else y needs no special rule at all: it is just b applied to x and y. And p and q is p applied to q and p: if p is true it chooses q, and if p is false it chooses p, which is false. Or is the mirror image. Our reducer confirms all four rows of each table, in four steps each, and every answer comes out as the function true or the function false itself.
Numbers are repetitions. The numeral n is the function that takes f and x and applies f to x, n times. Zero applies it no times and returns x. One applies f once. Two wraps x in two applications of f, and so on: picture each f as a box around the one inside. Successor takes a numeral n, lets it apply f n times, and then applies f once more, on the outside.
With repetition, arithmetic falls out. Plus m n applies f m more times on top of n applications. Times m n takes the function apply f n times, and repeats that m times. And power is the strangest and shortest of all: n applied to m. Apply the function times m, n times over, starting from one. Our reducer computes three plus four, three times four and two to the third, in six, nine and sixteen beta steps, and each normal form is exactly the expected numeral.
Pairs encode two values behind a selector. First applies the pair to true; second applies it to false. These are functions selecting one component. For predecessor, counting forward is easier than undoing a function application. Kleene's construction carries two consecutive counts. Start at zero, zero, and update a, b to b, successor b, once per input iteration. For a positive numeral n the first component ends at n minus one. At zero it stays zero, so predecessor saturates rather than producing a negative numeral. Our full normal-order reducer uses nine beta steps for zero, then ten n plus six for the displayed positive numerals. Those counts belong to this encoding and reduction strategy. They count beta contractions, not the cost of copying syntax trees, memory allocation or machine time.
Lists follow the same pattern. A list is a function of two arguments, c and n. The empty list returns n. A list with head h and tail t applies c to h and to whatever the tail produces. So the list one, two, three is c one, c two, c three, n. A list is its own loop: hand it addition for c and zero for n, and it sums itself. The same idea made the numerals work: a data structure is defined by what you can do with it. Booleans, numbers, pairs and lists, built from lambda, variables and application, and nothing else.
4Recursion without namesGraduate2 min
How can a function call itself, when functions have no names? We would like to define factorial: one if n is zero, and otherwise n times factorial of n minus one. But in the lambda calculus there is no way to write the name fact inside its own definition. So make the recursive call a parameter. F takes a function, self, and returns a factorial that calls self for the smaller case. F is an ordinary lambda term. What we want is a function fact such that F applied to fact is fact again. In the language of mathematics, fact is a fixed point of F. All we need is a way to find fixed points.
Haskell Curry's Y combinator finds them. Y takes f and applies lambda x, f of x x, to itself. Watch it run on some g. One step substitutes g. The next applies the self-application, and out comes g, applied to the very term we had a moment ago. So Y g reduces to g of something that is itself equal to Y g. Y g is a fixed point of g, for every g. Look closely and it is omega again: the same self-application that looped forever, with g wrapped around each copy, so each turn of the loop hands g one more chance to use itself.
Now combine everything so far. With Church numerals, booleans, multiplication and Kleene's predecessor, F is an ordinary term, and Y F is factorial. Our reducer evaluates it for n from zero to four, and the answers are one, one, two, six and twenty-four. Recursion, from functions that have no names. But look at the cost. Four factorial takes over ten thousand steps, and each extra n multiplies the work. Normal order copies arguments before evaluating them, and then evaluates each copy separately. The next chapter is about exactly this.
5Evaluation strategiesGraduate3 min
Reduction strategies choose which work to perform. Full normal order chooses the leftmost outermost redex, including redexes under lambdas. Full applicative order chooses the leftmost innermost redex, again including lambda bodies. Weak evaluation stops beneath an unapplied lambda. Call-by-name passes the argument unevaluated and can substitute or revisit it each time it is used. Our comparison uses this pure weak model. Call-by-value evaluates an argument to a value before beta application. Many languages use a form of this rule; their sequencing and effects add language-specific details. Call-by-need adds sharing: a suspended argument is evaluated when demanded and its result is reused. This is a model for lazy implementations such as Haskell, with separate costs for allocation, forcing and retaining thunks. Weak-head results and full beta normal forms are different stopping criteria.
Here is the term from chapter two: a function that returns its first argument, applied to a and to omega. Normal order and call-by-name reduce the outside first, and finish in two steps with the answer a. Applicative order and call-by-value insist on evaluating omega before the call, and never finish. The function did not even need omega. Strategies that wait never do worse at finding an answer, which the end of this chapter makes precise.
Strategies also differ in cost. We ran three functions on the same argument, three times three, on a machine that counts beta steps. When the body uses its parameter three times, call-by-name evaluates the argument three times over: forty-three steps against thirty-three. When the body never uses it, call-by-value evaluates it anyway, and loses. Call-by-need wins both ways: it evaluates an argument at most once, and only if it is needed. Christopher Wadsworth described this sharing in 1971, and it is how Haskell runs.
One theorem settles which strategy is safest. If a term has a normal form at all, normal order will reach it. Curry and Feys proved this standardization theorem in 1958. So normal order never misses an answer that exists. It may waste work, and real languages mostly choose call-by-value for speed and predictability, accepting that some programs loop that need not. But could two strategies find different answers? That is the subject of the next chapter.
6Church–Rosser, and de BruijnGraduate2 min
Compare all reductions of this precisely parenthesized term. Lambda x, x x is applied to the whole argument consisting of the identity applied to z. There are two redexes initially. Reducing the outer one copies the argument; reducing the inner one first avoids that duplication. The computed graph identifies terms up to renaming bound variables. It has six nodes and seven reduction edges. This finite graph is fully explored, and every maximal reduction path reaches z z. That exact example illustrates confluence. The general theorem also covers terms with infinite paths; it does not say that every path in every lambda term terminates.
Church and Rosser's theorem concerns beta reduction in the pure calculus. If M reduces by zero or more steps to N one and N two, some P is reachable from both. The four sides of this diamond are reduction sequences, not necessarily single steps. Thus a beta normal form, if one exists, is unique up to renaming bound variables. Effects or additional rewrite rules need their own confluence argument. Ordinary one-step beta reduction lacks the diamond property because a contracted redex can copy another redex. The formal parallel-reduction relation permits coordinated contraction with substitution; it has the joining property used to establish confluence. It is a proof device, not a claim that arbitrary overlapping edits can be performed independently.
7Simple typesDegree4 min
Add booleans and numbers to the calculus, and some programs make no sense. If zero then true else false. The successor of true. The predecessor of a boolean. True applied to zero. Is zero of a function. Each one stops somewhere that is not an answer, with no rule to apply. It is stuck. On a real machine, the same mistake is a crash, or worse, a silent wrong answer computed from bits that meant something else. Types rule such programs out before they run. Robin Milner put it in a slogan in 1978: well-typed programs cannot go wrong. The next two chapters prove it.
The simply typed lambda calculus adds types to the language. A type is bool, or nat, or a function type A arrow B. Terms are as before, with booleans, numbers and their operations, except that every lambda states the type of its parameter. A arrow B is the type of functions from A to B. Arrows group to the right, so nat to nat to nat is a function of two numbers. Church introduced this system in 1940, not for programming, but to keep logic consistent: the untyped calculus could express paradoxes.
The type checker applies a handful of rules, written as in Part 13: what must be known above the line, what follows below. A variable has the type the context gives it. To type a function, assume its parameter has the declared type, and type the body; the function's type is the arrow from one to the other. A function from A to B, applied to an A, gives a B, and only an A will do. The successor of a number is a number, and an if needs a boolean condition and two branches of the same type. That is the whole checker.
Typing a whole term builds a tree of rules, called a derivation. Here our checker types lambda x of type nat, successor of x, applied to two. At the bottom is the conclusion: the term has type nat, by the application rule. Above it, its two premises: the function has type nat to nat, by the abstraction rule, which in turn rests on typing successor of x with x assumed to be a nat. And the argument two is a nat, as the successor of the successor of zero. Every well-typed term has such a tree, and the checker's work is exactly to build it. For a term that applies twice to successor and three, the tree has sixteen rules.
Typed terms run the same way as before, one small step at a time, by call-by-value. Twice, applied to successor and three. First the function position is reduced, substituting successor for f. Then the argument three goes in. The inner application must finish before the outer one can fire, and the answer is five. Each step is justified by a rule, named on the left, and the next chapter proves something about every such step.
8Well-typed programs cannot go wrongGraduate3 min
Milner's slogan is a theorem with two halves. Progress: a closed well-typed term is either a value, a finished answer, or it can take a step. It is never stuck. Preservation: if a well-typed term takes a step, the result has the same type. Put them together along any run of the program. Each term has type T, by preservation, so each one is either an answer or can step again, by progress. A well-typed program never reaches a stuck state.
The proofs go by induction on the typing derivation, one case per rule. Here is the interesting case of progress. The term is an application, f of a, where f has type A to B and a has type A. By induction, f is a value or can step. If it can step, so can f of a. If f is a value, then because its type is an arrow, it must be a lambda: the only values of function type are functions. This little lemma, canonical forms, is where the types do their work. Then the argument is a value or can step, and if it is a value, the whole term is a redex. For an if, the condition is either a step away or a value of type bool, which can only be true or false. In every case, the types say which values can appear in which positions, and no stuck combination survives.
Preservation rests on one lemma. The only step that changes a term's shape much is beta reduction, which substitutes an argument for a parameter. When we typed the redex, we typed the body t assuming x is an A, and we typed the argument s as an A. The substitution lemma says that putting a real A where an A was assumed leaves the body's type unchanged. It is proved, in turn, by induction on the derivation of t. With it, preservation follows case by case.
Finite checks exercise the implementation of the safety rules. The generator constructs five thousand closed, well-typed terms from its stated grammar and seed. In the recorded run, all finish after fifty thousand five hundred and sixteen small steps in total, with typing checked after every step. No sampled state is stuck and no step changes its type. The longest sampled run takes forty-seven steps. That bound belongs only to these generated terms. The next chapter's normalization theorem explains why every term in the recursion-free typed calculus terminates, without giving this particular sample bound to all programs.
9Why the typed core terminatesGraduate3 min
Try typing lambda x, x x with finite simple types. In its function position, x must have some arrow type A to B. The same x is also its own argument, which must have type A. Simple typing gives that binder one monomorphic type. Unification therefore demands A equals A to B, with A occurring inside its own proposed definition. No finite simple type solves this equation. Recursive-type systems or richer polymorphic rules are different systems and require their own reasoning. Our Hindley Milner engine rejects this application with its occurs check. Omega and Y are untypable in the recursion-free simply typed calculus. Their rejection is a fact about this typing discipline; it is not a claim that every language with static types rejects all self-application or recursion.
In fact no typed term runs forever. William Tait proved in 1967 that every well-typed term of the simply typed calculus reaches a normal form, whichever order of reduction you choose. The obvious proof by induction on the size of the term fails, because a beta step can make a term bigger, by copying its argument. Tait's idea was to prove something stronger, defined by induction on the type. A number is good if it terminates. A function is good if it sends every good argument to a good result. Then show that every typed term is good, and every good term terminates. This method, now called logical relations, has been the workhorse of type theory ever since.
The experiment compares two generated populations. Of two thousand random closed untyped terms, one hundred and thirty-six do not finish within four hundred normal-order steps. That means the budget was exhausted; it does not independently prove that each of those terms diverges. The sampling grammar and seed define this population. All five thousand terms in the separate well-typed sample finish within the evaluator's limits. No finite experiment establishes universal termination. For the recursion-free simply typed calculus, strong normalization supplies the general theorem. The bar chart reports the samples; the proof explains the model's guarantee.
Strong normalization has a precise boundary. The simply typed calculus without general recursion cannot express a divergent computation, so it is not Turing complete. Diagonal arguments also restrict universal evaluation with a common type of program codes. Encoding assumptions matter: differently typed notions of self-interpretation need separate treatment. A general fixed-point operator changes the calculus. Given a function from T to T, fix produces a T, and its unfolding can continue forever. Safety can survive this extension even though termination does not. ML, Haskell and OCaml support general recursion. Proof assistants keep their trusted logical core consistent by restricting recursive definitions or requiring termination arguments. Their executable facilities can also include partial, unsafe or noncomputable features with carefully separated trust rules. The theorem concerns the specified core, not every command a proof-assistant installation can execute.
10Hindley–Milner inferenceGraduate4 min
In the hook, nobody wrote a type, yet the machine knew them all. Here is how. Take the function that applies f twice. Give each unknown a type variable: f has some type alpha, x some type beta. Every use adds an equation. f applied to x says alpha must be a function from beta to some gamma. And f applied to f of x says alpha is also a function from gamma to some delta. Inference is solving these equations between types, which is called unification.
Alan Robinson gave the algorithm in 1965, for automated theorem proving. An equation between a variable and a type binds the variable to that type, everywhere it appears. An equation between two function types splits into two equations: arguments equal, results equal. Two different type constructors, like int and bool, cannot be equal: that is a type error. And a variable cannot be bound to a type that contains it: that would be the infinite type of omega. When unification succeeds, it finds the most general solution, of which every other solution is a special case.
Here is our engine's own trace for twice. It assumes fresh variables for f and x. From f of x it binds f's variable to a function from x's variable to a new one. From the outer application it must unify that function type with another, which splits into two bindings. What is left is the principal type: for any type tick a, a function from tick a to tick a, then a tick a, gives a tick a. Composition comes out just as neatly, with three independent type variables. This is algorithm W, from Milner's 1978 paper; Roger Hindley had found the principal types of combinatory logic in 1969.
Let-polymorphism adds a controlled form of reuse. Bind the identity with let and use it at int and bool: the pair has type int times bool. A lambda parameter, used at both types in ordinary Hindley Milner, is instead rejected. Generalization quantifies the inferred type variables that are not free in the surrounding type environment. Variables tied to an outer parameter must stay shared. Each use then instantiates the quantified variables freshly. A lambda-bound parameter is monomorphic within its scope. This distinction is enough for principal types and decidable inference in the pure Hindley Milner system; mutation requires further restrictions such as ML's value restriction. Full implicit System F typability is undecidable. More expressive annotated or restricted systems can still have decidable checking or inference, so there is no single boundary saying that all richer polymorphism is impossible.
Here is the whole Job, as the hook promised. Eleven definitions, a few hundred unifications, and not one annotation. Reverse works on lists of anything. Lower and is letter work on character codes. Bump and count work for any type of word that supports equality, and insert and sort for any pair whose second part is a count. The type variables are a precise statement of what each function does not care about, discovered rather than declared.
11Polymorphism and free theoremsGraduate3 min
System F makes polymorphism explicit and allows quantifiers inside function types. Types gain for all alpha. Terms gain type abstraction, capital lambda alpha, and explicit type application. Girard introduced the system in 1972 and Reynolds independently in 1974. The identity first receives a type and then a value of that type. A function can now receive a polymorphic identity and instantiate it at both int and bool. The displayed pair uses the corresponding product extension. Ordinary Hindley Milner does not allow this higher-rank parameter without an extension. Distinguish two tasks. Checking fully annotated Church-style System F is decidable. Finding omitted type abstractions and applications in the unrestricted Curry-style typability problem is undecidable. Annotations or restricted inference systems make useful intermediate choices.
Church encodings receive explicit polymorphic types here. A boolean chooses between two arguments of one arbitrary type. A numeral iterates a function, and a list provides a fold over its element type. The quantifiers let callers choose the result type. For closed terms in the pure total system, normalization and parametricity give these encodings their expected behavior. System F is strongly normalizing, yet represents a large class of total numerical functions related to second-order arithmetic's provably total functions. That is a precise proof-theoretic connection, not a claim that every mathematical function is computable or expressible. General recursion, effects and additional primitives require a fresh analysis of these properties.
A type can imply an equation when the language supplies parametricity. Work first in a pure, total setting. A closed function of type for all alpha, alpha to alpha must return its argument: it has no other alpha to manufacture. At for all alpha, alpha to alpha to alpha, it must consistently choose one of its two arguments, giving a Church boolean. For a function from lists of alpha to lists of alpha, behavior can depend on list shape while elements can only be rearranged, dropped or copied. It cannot inspect an arbitrary alpha. The square commutes: map f after g equals g after map f, for total f and finite lists. Reynolds's parametricity supports the proof; Wadler popularized such free theorems. With divergence, effects, runtime type inspection or primitives such as Haskell's seq, the assumptions and resulting theorem need adjustment.
12Propositions as typesGraduate4 min
Here is the deepest idea in this part. Read a type as a proposition. A function type, A to B, is the proposition A implies B, and a function of that type is a proof of it: give it evidence for A and it produces evidence for B. A pair is a proof of A and B. A tagged union, an A or a B together with which one, is a proof of A or B. The empty type, with no values at all, is falsehood, and not A is a function from A to the empty type, which could never actually be called. A proof is a program. And simplifying a proof, removing a detour through a lemma, is exactly running the program by beta reduction. Haskell Curry noticed the first signs of this in 1934; William Howard wrote it down in full in 1969.
If proofs are programs, a theorem prover is a program synthesizer. Our prover searches for a lambda term of a given type. A implies B implies A is the function that takes x and y and returns x: the constant combinator. Composition proves the syllogism: from A implies B and B implies C, A implies C. Swapping a pair proves that and is commutative. Case analysis on a tagged union proves that or can be eliminated. And the last row is a small gem: not not of A or not A. It sounds like excluded middle, but it is provable without it. The program is a trick: it is handed a refutation x, and uses it against itself.
Classical truth and constructive inhabitation differ in the stated logical core. Excluded middle, double-negation elimination, Peirce's law and the displayed half of de Morgan's law all pass classical truth tables. Here A and B are arbitrary proposition variables. Our proof search finds no pure intuitionistic proof terms for them. A failed finite search alone would not prove nonexistence. The next panel supplies Kripke countermodels, and soundness of the logical rules turns those models into a non-inhabitation argument for this calculus. General recursion, control operators or additional axioms change that calculus. A constructive proof of A or not A must provide either evidence for A or a refutation, together with the selected alternative. There is no uniform term supplying that choice for every arbitrary A under these rules. Particular propositions can still have decidable proofs or refutations; this claim does not deny ordinary decision algorithms.
To show that no program exists, we need a world where the formula fails and programs still make sense. Saul Kripke supplied one in 1965. Picture states of knowledge, which only grow, upward. In the lower world, w zero, we do not yet know A. In the world above it, we do. At w zero, A is not known. Not A is not known either, because not A would mean A can never become known, and above us it does. So A or not A fails at w zero. And every formula that has a program holds in every such model. So excluded middle has no program. Our search finds a two-world model like this for each of the first three laws, and a three-world model for de Morgan's.
13Dependent and linear typesGraduate3 min
So far, types and values have lived apart. Dependent types let a type mention a value. Vec A n is the type of lists of A of length exactly n: the length is part of the type. Appending a vector of length m to one of length n gives length m plus n, and the type checker verifies the arithmetic. Head accepts only vectors of length n plus one. Taking the head of an empty list is no longer a crash at run time; it is a type error. And zip demands two vectors of the same length.
Dependent function and pair types express two forms of evidence. Pi is a function type whose result can depend on its argument, such as a function taking n and returning a vector of length n. It corresponds to universal quantification under the propositions-as-types interpretation. Sigma pairs a witness with evidence depending on that witness: a length together with a vector of that length. It corresponds to an existential statement with explicit data. Martin-Lof's type theories and the calculus of constructions helped build constructive foundations and proof assistants. Rocq, Agda and Lean provide different systems; their kernels and computational features should not be identified with one tiny calculus. When types contain programs, definitional equality may require computation. The trusted logical core needs controlled reduction and recursion to preserve its metatheory. Executable partial or unsafe facilities can exist outside that core, with explicit restrictions on their use in proofs.
A different refinement counts uses. Our checker counts how many times each classic combinator uses each parameter. The identity, composition and flip use every argument exactly once: they are linear. The constant function throws its second argument away: affine, at most once. W and S duplicate one: relevant, at least once. Jean-Yves Girard's linear logic, from 1987, treats assumptions as resources that are consumed when used. In programming the resources are real: a file handle that must be closed exactly once, a lock, a block of memory that must be freed once and never used afterwards.
Rust makes ownership and borrowing concrete. The displayed String is not a Copy value. Assigning it to kept transfers ownership, so using the moved word is rejected with E zero three eight two. This is an affine discipline: a resource can be dropped as well as consumed once. Copy types follow different rules. The second example keeps a shared reference into a vector live while requesting a mutation that could reallocate its storage. The borrow checker rejects the conflict. Shared and exclusive access rules, lifetimes and library contracts work together; the slogan many readers or one writer is an introduction, not the entire aliasing model. These mechanisms support memory and data-race safety for safe code when unsafe dependencies uphold their obligations. They do not exclude memory leaks, deadlocks, logic errors or all thread races. The recorded compiler messages demonstrate these two examples on this Rust version.
14Data, subtyping and gradual typesIndustry4 min
Algebraic data types describe alternatives and their fields. A shape can be a circle with a radius or a rectangle with width and height: a sum of products. The propositions-as-types dictionary interprets these constructors as choices and pairs, with the logical assumptions stated earlier. Pattern matching inspects the constructor. Exhaustiveness checking can report missing cases, but language settings, wildcards and guards affect the guarantee. Adding a triangle does not force every match to change if a wildcard already handles it. Nested patterns need more analysis than counting constructor names. An option type makes absence an explicit alternative. It can rule out an unhandled null dereference when programs respect its interface; extracting a value can still require handling the empty case. Make illegal states unrepresentable is a useful design goal.
Subtyping specifies which replacements preserve an interface's guarantees. A value of subtype S can be used where a T is expected under the language's subtype rules. A Dog can supply an Animal interface. For ordinary function subtyping, the replacement accepts at least the promised inputs and returns a sufficiently specific result. A function that can handle every Animal can serve a caller that supplies only Dogs. Results are covariant; arguments are contravariant. The arrows in the rule point in opposite directions for that reason. An unchecked mutable array both produces and consumes elements. Allowing Dog arrays to be used as writable Animal arrays would let a caller insert a Cat. Invariance prevents that substitution. Read-only views or runtime store checks permit other designs, with different contracts and costs.
This recorded TypeScript example shows an intentional soundness tradeoff. The Dog array is assigned to an Animal-array variable. A Cat is pushed through that alias, and the original Dog-array expression later calls bark on the new element. The recorded compiler accepts it with exactly the displayed strict flag. Strict is a bundle of checks, not every possible checking option; additional indexed-access checks can report other concerns. Running the emitted JavaScript with the recorded Node version raises a TypeError because bark is not a function. The types were erased and supplied no runtime store barrier. Java's covariant reference arrays use a different contract: a runtime component-type check can reject an incompatible store. Compare the static rules and runtime checks together. Useful typing tools can deliberately offer less than the no-stuck-state theorem of a sound calculus.
Gradual typing studies how precise and imprecise type information can coexist. A gradual unknown type is related to other types by a consistency relation, with checks determined by the chosen semantics. TypeScript's any, its unknown type and Python's optional type hints make different choices; these mechanisms should not all be treated as one sound cast calculus. In the displayed TypeScript program, any allows forty-two to pass to a string-typed parameter. Erasure leaves ordinary JavaScript execution, and the result printed here is NaN. No runtime string contract was inserted. Sound gradual systems can insert boundary checks and higher-order wrappers. A 2016 Typed Racket study measured very large slowdowns for some partially typed configurations. That is a historical workload result, not a bound for every current implementation. Coercion composition and other techniques improve particular costs. The research exercise asks for a stated semantics and baseline before discussing guarantees.
15Frontier: the edges of type theoryResearch4 min
Worst-case inference complexity and a measured workload answer different questions. We repeat the Job's eleven definitions in up to thirty-two copies, giving three hundred and fifty-two definitions. The graph shows recorded host times for this synthetic family. Unification-call counts grow exactly with the copy count; elapsed times also include implementation and scheduling effects and need not form a straight line. Shared type graphs avoid expanding repeated subtypes in the nested-let example. Complexity analyses parameterize more than source size, including type-scheme size and let structure; bounded nesting alone is not a complete universal linear-time guarantee. McAllester's 2003 work is one source for that analysis. To investigate an implementation, state the family and representation, measure work as well as wall time, and vary the parameters. A small favorable graph cannot establish how every real program behaves.
Refinement types attach logical predicates to values. In the displayed interface, get receives an array and an index satisfying zero less than or equal to i, and i less than the array length. The caller must establish that condition. Type checking generates verification conditions for a selected logic. An SMT solver may prove them, find a countermodel, or return unknown or a timeout. Solver failure to prove a condition does not by itself prove the program wrong. LiquidHaskell, F star and Dafny combine types, specifications and automated proof in different ways. Their verified properties depend on the stated specifications, supported theories and trust boundaries. The engineering challenge is to choose useful predicates and automation while keeping proof obligations understandable. Refinements can automate some proofs; they do not remove the need to define or justify the property.
Identity types give equality mathematical structure. A proof that a equals b is itself a term of an identity type, and proofs can have further equalities between them. Homotopy type theory interprets these witnesses as paths and higher paths. Voevodsky's univalent foundations helped develop this connection. Univalence relates equality of types to equivalence of types: the canonical map from type equalities to equivalences is itself an equivalence. This makes precise a way of transporting mathematical structure across equivalences. Adding an axiom without computation rules can leave closed data expressions without a canonical numeral normal form. That is a question about computation and canonicity in the extended theory, not a counterexample to the earlier theorem about our original simply typed calculus. Cubical type theories provide computational treatments of univalence. Their exact normalization and canonicity results depend on the chosen calculus. Implementations such as Cubical Agda turn these ideas into proof-assistant tools.
In a language with unrestricted effects, an ordinary int-to-int type does not list every action a function may perform. It might read a file, raise an exception or diverge. An effect system adds information about such behavior; its guarantees depend on which effects it tracks. An algebraic effect operation sends a request to a handler. The handler receives the operation's data and a captured delimited continuation, which it may resume according to the language's rules. The handler is not itself just the continuation. OCaml 5 introduced effect handlers in 2022, while languages such as Koka track effects in types. These systems differ in typing and continuation discipline. Usable interfaces, compositional reasoning and efficient implementations remain active design problems. Stating the operation and resumption rules lets us reason about a specific mechanism instead of treating all effects as interchangeable.
Recap, problems, and where this comes backAll tracks2 min
We built lambda terms and capture-avoiding substitution, then compared beta reduction with weak evaluation. Church encodings supplied data, and fixed points supplied recursion, with delayed branches needed for the strict factorial. Confluence made beta normal forms unique up to alpha equivalence, while simple types supported progress, preservation and strong normalization in the specified recursion-free calculus. Random runs checked implementations, not the general proofs. Hindley Milner inferred the Job's types; shared type graphs distinguished representation blowup from typability complexity. Propositions-as-types connected proof search with programs, with Kripke countermodels certifying the displayed intuitionistic non-theorems.
Where this comes back. Part 15 turns the lambda core into a real runtime, with environments, closures, continuations, a virtual machine and a garbage collector, and runs the Job on it for ledger row six. Part 25 proves the diagonal and recursion theorems that this part leaned on. Part 43 puts types on the boundaries between services. Part 54 proves programs correct in Lean and Rocq. Part 55 returns to Rust, and Part 58, in the research tier, asks what programs mean.
The notes contain six worked exercises. Compare reduction orders with exact parentheses; measure a stated Church-subtraction strategy; prove the progress cases; and infer a principal type while respecting the environment. The build exercise starts with a precisely limited constructor-pattern language before extending exhaustiveness checking. The starred investigation reproduces known space-efficient gradual coercions, then asks for one explicit extension and cost claim. A research prompt begins with definitions and a literature check; the presence of a star does not make an already solved subproblem open.
Next time. The lambda core gets a runtime: closures and environments instead of substitution, continuations that turn the stack into data, a bytecode virtual machine, and a garbage collector kept correct by an invariant stated in three colours. Part 15, Runtimes.
The books and papers this part follows are on screen and in the notes. Thank you for watching.
Where it goes next. Part 15 gives the lambda core a runtime (environments, closures, continuations, a virtual machine and a garbage collector) and runs the Job on it. Part 25 proves the diagonal and recursion theorems used here, Part 43 puts types on the boundaries between services, Part 54 proves programs correct in Lean and Rocq, Part 55 returns to Rust, and Part 58 asks what programs mean.
Key results
The part's results in one place, for revision.
Try it
Lab 14 · Church arithmetic, confluence and type safety, by machine
With the series' reducer, compute on Church numerals and count the beta-steps (the predecessor costs 10n + 6); build the whole reduction graph of small terms and check that every pair of reducts meets again; then compare random untyped terms, some of which never stop, with random well-typed terms, on which progress and preservation are checked at every step.
python -m videos.cs.labs 14
needs numpy, scipy, matplotlib · download lab14.py ·
source on GitHubplus 1 1 2 in 6 beta-steps
times 5 4 20 in 13 beta-steps
predecessor of 0..10, beta-steps 9 16 26 36 46 56 66 76 86 96 106
the film's count 9 at zero, then 10n + 6
reduction graph 6 terms, 7 steps, 1 normal form, confluent
reduction graph 30 terms, 93 steps, 1 normal form, confluent
random reduction graphs 30 of 30 confluent, at most one normal form (largest: 55 terms)
untyped terms still running after 400 steps 21 of 300 (the film: 136 of 2,000)
well-typed terms that stop 400 of 400, the longest after 25 steps
typed steps checked for progress and preservation 2,670, none stuck, none changing type
One rule computes arithmetic, any two reduction paths can be rejoined, and a type derivation buys two guarantees an untyped term does not have: it never gets stuck and, without fix, it always stops.
The code (130 lines; it asserts its own result)
"""Lab 14: count beta-steps in Church arithmetic, check confluence on whole reduction graphs, and run the safety theorems."""
from videos.coursekit import labs
import random
import numpy as np
from explainer.cs.lam import App, Lam, Var, church, parse, unchurch
from explainer.cs.lang.lam import reduce as R
from explainer.cs.lang.lam import stlc
TITLE = "Church arithmetic, confluence and type safety, by machine"
GOAL = ("With the series' reducer, compute on Church numerals and count the beta-steps (the predecessor costs "
"10n + 6); build the whole reduction graph of small terms and check that every pair of reducts meets "
"again; then compare random untyped terms, some of which never stop, with random well-typed terms, on "
"which progress and preservation are checked at every step.")
TASKS = [
"Reduce R.apply(R.lib('pow'), church(2), church(n)) for n = 1..6 and plot the steps. Is the growth linear in n or in 2^n?",
"Run r'(\\x y. y) ((\\x. x x) (\\x. x x)) z' under each of 'normal', 'applicative', 'name' and 'value'. Which strategies find the normal form?",
"In typed_terms, raise depth from 5 to 7. How does the longest run change, and why can no depth make a typed term loop?",
]
BUDGET = 400 # beta-steps allowed to an untyped term, as in the film
FILM = ((r"(\x. x x) ((\y. y) z)", 6, 7), (r"(\x. x x) ((\y. (\z. z) y) ((\w. w) v))", 30, 93)) # terms, steps
def untyped(rng, depth, env=()):
"""A random closed lambda term (the film's generator: variables 30%, abstractions 30%, applications 40%)."""
r = rng.random()
if depth <= 0:
return Var(rng.choice(env)) if env else Lam("v0", Var("v0"))
if env and r < 0.3:
return Var(rng.choice(env))
if r < 0.6:
x = f"v{len(env)}"
return Lam(x, untyped(rng, depth - 1, env + (x,)))
return App(untyped(rng, depth - 1, env), untyped(rng, depth - 1, env))
def typed_terms(n, seed, depth=5):
"""Steps to a value for n random closed well-typed terms; progress and preservation asserted at every step."""
rng = random.Random(seed)
types = [stlc.BOOL, stlc.NAT, stlc.arrow(stlc.NAT, stlc.NAT), stlc.arrow(stlc.BOOL, stlc.NAT)]
steps = []
for i in range(n):
T = types[i % len(types)]
t = stlc.gen(T, depth, rng)
k = 0
while not stlc.is_value(t):
r = stlc.step(t)
assert r is not None, f"progress fails: {stlc.show(t)} is stuck"
t = r[0]
assert stlc.typecheck(t)[0] == T, f"preservation fails at {stlc.show(t)}"
k += 1
assert k < 10_000, "a well-typed term that does not stop"
steps.append(k)
return np.array(steps)
def run(seed=0):
rng = np.random.default_rng(seed)
pyrng = random.Random(seed)
lab = labs.Lab()
# 1. arithmetic with functions alone, counted in beta-steps (normal order)
for name, op in (("plus", lambda a, b: a + b), ("times", lambda a, b: a * b)):
for _ in range(4):
a, b = (int(v) for v in rng.integers(1, 6, 2))
k, t = R.run(R.apply(R.lib(name), church(a), church(b)))
assert unchurch(t) == op(a, b), f"{name} {a} {b} gave {unchurch(t)}"
lab.row(f"{name} {a} {b}", f"{unchurch(t)} in {k} beta-steps")
ns = np.arange(0, 11)
pred = []
for n in ns:
k, t = R.run(R.apply(R.lib("pred"), church(int(n))), max_steps=5000)
assert unchurch(t) == max(int(n) - 1, 0)
pred.append(k)
pred = np.array(pred)
lab.row("predecessor of 0..10, beta-steps", " ".join(str(k) for k in pred))
lab.row("the film's count", "9 at zero, then 10n + 6")
assert pred[0] == 9 and np.array_equal(pred[1:], 10 * ns[1:] + 6), "Kleene's predecessor costs 10n + 6 steps"
# 2. Church-Rosser on whole reduction graphs
for src, terms, steps in FILM:
nodes, edges, normal = R.graph(parse(src), limit=500)
assert (len(nodes), len(edges), len(normal)) == (terms, steps, 1) and R.confluent(parse(src), 500)
lab.row("reduction graph", f"{len(nodes)} terms, {len(edges)} steps, {len(normal)} normal form, confluent")
graphs = most = 0
while graphs < 30:
t = untyped(pyrng, 5)
nodes, _, normal = R.graph(t, limit=60)
if 3 <= len(nodes) < 60: # the whole graph was explored
graphs += 1
most = max(most, len(nodes))
assert len(normal) <= 1 and R.confluent(t, 60), "two reducts that never meet"
lab.row("random reduction graphs", f"{graphs} of {graphs} confluent, at most one normal form (largest: {most} terms)")
# 3. untyped terms can run forever; well-typed terms cannot, and cannot get stuck
n_untyped = 300
stopped = np.array([k for k in (R.run(untyped(pyrng, 7), "normal", max_steps=BUDGET, max_size=3000)[0]
for _ in range(n_untyped)) if k is not None])
running = n_untyped - len(stopped)
typed = typed_terms(400, seed + 1)
lab.row(f"untyped terms still running after {BUDGET} steps", f"{running} of {n_untyped} (the film: 136 of 2,000)")
lab.row("well-typed terms that stop", f"{len(typed)} of {len(typed)}, the longest after {typed.max()} steps")
lab.row("typed steps checked for progress and preservation", f"{typed.sum():,}, none stuck, none changing type")
assert running >= 3, "some random untyped terms should exhaust the budget"
assert typed.max() < BUDGET
lab.note = ("One rule computes arithmetic, any two reduction paths can be rejoined, and a type derivation buys two "
"guarantees an untyped term does not have: it never gets stuck and, without fix, it always stops.")
fig, ax = labs.figure(2, size=(11, 4.4))
ax[0].plot(ns[1:], 10 * ns[1:] + 6, color=labs.GOLD, label="10n + 6")
ax[0].plot(ns, pred, "o", color=labs.BLUE, label="Kleene's predecessor, measured")
ax[0].set(title="Beta-steps to compute n - 1 on Church numerals", xlabel="n", ylabel="beta-steps (normal order)")
ax[0].legend()
edges = np.array([0, 1, 2, 4, 8, 16, 32, 64, 128, 256, BUDGET])
x = np.arange(len(edges))
hu = np.append(np.histogram(stopped, edges)[0], running) / n_untyped
ht = np.append(np.histogram(typed, edges)[0], 0) / len(typed)
ax[1].bar(x - 0.2, ht, 0.4, color=labs.GREEN, label="well-typed (simply typed calculus)")
ax[1].bar(x[:-1] + 0.2, hu[:-1], 0.4, color=labs.BLUE, label="untyped")
ax[1].bar(x[-1:] + 0.2, hu[-1:], 0.4, color=labs.RED, label=f"untyped, still running at {BUDGET}")
ax[1].set_axisbelow(True)
ax[1].set(title="How long random terms run", xlabel="steps to a normal form or a value", ylabel="share of terms",
xticks=x, xticklabels=["0", "1", "2-3", "4-7", "8-15", "16-31", "32-63", "64-127", "128-255", "256-399",
"never?"])
ax[1].tick_params(axis="x", labelrotation=35)
ax[1].legend()
lab.fig = fig
return lab
Now change it
- Reduce R.apply(R.lib('pow'), church(2), church(n)) for n = 1..6 and plot the steps. Is the growth linear in n or in 2^n?
- Run r'(\x y. y) ((\x. x x) (\x. x x)) z' under each of 'normal', 'applicative', 'name' and 'value'. Which strategies find the normal form?
- In typed_terms, raise depth from 5 to 7. How does the longest run change, and why can no depth make a typed term loop?
Problems, with solutions
Try each problem before opening its solution.
-
Two orders. Reduce
(λx y. y x x) ((λz. z) a) (λw. w)to normal form by normal order and by applicative order, count the steps, and explain the difference.Solution
Normal order (5 steps): substitute the unreduced argument
(λz. z) afor x, giving(λy. y A A) (λw. w)with A =(λz. z) a; then(λw. w) A A, thenA A, then reduce each copy of A:a A,a a. Applicative order (4 steps): reduce A toafirst, then(λx y. y x x) a→λy. y a a, then apply it to the identity and reduce(λw. w) a a→a a. Normal order copied the argument before evaluating it, so it evaluated it twice; applicative order evaluated it once. Both reach the same normal form, as Church–Rosser promises. (Our reducer,reduce.run, gives 5 and 4.) -
More arithmetic, with a cost model. Define exp, iszero and saturating sub on Church numerals. Count beta contractions for an algorithm that fully normalizes each predecessor result before the next application. Explain why a universal Theta(m*n) runtime claim is unjustified.
Solution
exp = λm n. n m,iszero = λn. n (λz. false) true, andsub = λm n. n pred m. The result is max(m−n,0). For this library's predecessor, full normal-order contraction counts are p(0)=9 and p(k)=10k+6 for positive k. Normalizing each intermediate numeral gives sum(p(max(m−i,0)), i=0..n−1). With r=min(m,n), this is r(10m+6)−5r(r−1)+9(n−r). Thus this particular contraction-count algorithm has order n+m*min(m,n) for nontrivial inputs, including saturation at zero. Counting the four outer beta contractions in the literalsubterm matches our 63 sampled (m,n) pairs, but finite agreement is not a universal complexity proof for every reducer. At n=0 the term returns an already present numeral in four contractions; printing its m applications or copying syntax has another cost. State the representation, stopping criterion, sharing and unit cost before comparing implementations. -
Two cases of progress. Prove progress for If and Succ, stating the canonical forms lemma you need.
Solution
Canonical forms: a value of type Bool is true or false; a value of type Nat is 0 or succ v with v a numeric value; a value of type A → B is a λ. Case If: ⊢ if c a b : T needs ⊢ c : Bool. By induction c is a value or steps. If it steps, E-If makes the whole term step. If it is a value, by canonical forms it is true or false, and E-IfTrue or E-IfFalse applies. Case Succ: ⊢ succ t : Nat needs ⊢ t : Nat. If t steps, so does succ t (E-Succ); if t is a value, it is a numeric value by canonical forms, so succ t is itself a value.
-
Inference by hand. Infer the principal type of
λf g x. g (f x) x, showing each unification.Solution
Assume f : α, g : β, x : γ.
f xforces α = γ → δ.g (f x)forces β = δ → ε.(g (f x)) xforces ε = γ → ζ. Substituting: f : γ → δ, g : δ → γ → ζ, x : γ, result ζ. Renaming, the principal type is('a -> 'b) -> ('b -> 'a -> 'c) -> 'a -> 'c, exactly what our engine reports, with the same three bindings in the same order. -
Build: a precisely scoped option type. Add an
'a option = None | Some of 'adeclaration and matches in which each constructor is followed only by distinct variable binders. Infer types and rewrite the Job's lookup to return an option.Solution
Give
Nonethe scheme forall a. a option andSomethe scheme forall a. a -> a option. Instantiate freshly at each use. In a match, unify the scrutinee with option tau, bind theSomefield at tau, and unify branch result types. In this shallow pattern fragment, coverage means both None and Some occur, or a final wildcard covers the remainder; reject duplicates or report them as unreachable. Merely counting top-level constructors does not check nested patterns such asSome (Some x)exhaustively. An extension to nested patterns needs recursive pattern-matrix specialization and default cases. Evaluate options as tagged values. Implementfind : 'a -> ('a * 'b) list -> ('a * 'b) option, then compare the rewritten Job withjob_referenceon empty input, repeated words, ties and absent keys. Equality constraints in a realistic ML require explicit treatment; our toy printer omits them. This is a build specification, not a claim that the current repository already implements user-defined ADTs. -
★ Investigation: space-efficient gradual checks. Reproduce a known coercion-composition scheme for a small higher-order gradual calculus, then state and investigate one extension.
Where to start. Fix the typed/untyped boundary semantics, observable errors, baseline program and cost model. A direct wrapper-chain implementation can accumulate proxies; known space-efficient coercions compose checks and prevent that growth. Reproduce that result before proposing a lower bound. Track maximum live coercion size, allocations, checks and runtime separately. Then choose one extension—such as mutable references with a specified semantics—and review existing results before claiming novelty. The 2016 Typed Racket study measured over 100× overhead in some tested configurations; that is a historical workload result, not a universal lower bound. A representation-space bound also does not establish a universal constant runtime-overhead factor. See Siek and Taha (2006), refined gradual criteria (2015), Grift (2019), and Space-Efficient Gradual Typing in Coercion-Passing Style (ECOOP 2020).
Notes and sources
Glossary
λ 演算 lambda calculus · 项 term · 抽象 abstraction · 应用 application · 自由变量 / 约束变量 free / bound variable · α 等价 alpha-equivalence · 变量捕获 variable capture · 避免捕获的代换 capture-avoiding substitution · β 归约 beta-reduction · 可约式 redex · 范式 normal form · 丘奇数 Church numeral · 丘奇编码 Church encoding · 不动点 fixed point · Y 组合子 Y combinator · 归约策略 reduction strategy · 正规序 / 应用序 normal / applicative order · 传名 / 传值 / 传需 call-by-name / -value / -need · 共享 sharing · 标准化定理 standardization theorem · 合流性 confluence · 丘奇– 罗瑟定理 Church–Rosser theorem · 平行归约 parallel reduction · 德布鲁因指标 de Bruijn index · 简单类型 simple types · 类型规则 typing rule · 推导 derivation · 卡住 stuck · 进展性 progress · 保持性 preservation · 典范形式 canonical forms · 代换引理 substitution lemma · 强正规化 strong normalization · 逻辑关系 logical relations · 类型推断 type inference · 合一 unification · 出现检查 occurs check · 主类型 principal type · let 多态 let-polymorphism · System F · 参数性 parametricity · 免费定理 free theorem · 柯里–霍华德对应 Curry–Howard correspondence · 直觉主义逻辑 intuitionistic logic · 克里普克模型 Kripke model · 续延 continuation · 依赖类型 dependent type · Π 类型 / Σ 类型 Pi / Sigma type · 线性 / 仿射 类型 linear / affine type · 所有权 ownership · 借用 borrowing · 代数数据类型 algebraic data type · 模式匹配 pattern matching · 子类型 subtyping · 协变 / 逆变 / 不变 covariant / contravariant / invariant · 渐进类型 gradual typing · 精化类型 refinement type · 一价公理 univalence · 效应处理器 effect handler
Sources
Canon. Books: Pierce, Types and Programming Languages; Harper, Practical Foundations for Programming Languages; Barendregt, The Lambda Calculus: Its Syntax and Semantics; Hindley & Seldin, Lambda-Calculus and Combinators; Sørensen & Urzyczyn, Lectures on the Curry–Howard Isomorphism; Girard, Lafont & Taylor, Proofs and Types; Martin-Löf, Intuitionistic Type Theory (1984).
Papers: Church, "An unsolvable problem of elementary number theory" (1936); Church & Rosser, "Some properties of conversion" (1936); Church, "A formulation of the simple theory of types" (1940); Curry & Feys, Combinatory Logic (1958); Robinson, "A machine-oriented logic based on the resolution principle" (1965); Kripke, "Semantical analysis of intuitionistic logic I" (1965); Tait, "Intensional interpretations of functionals of finite type I" (1967); Hindley, "The principal type-scheme of an object in combinatory logic" (1969); Howard, "The formulae-as-types notion of construction" (1969, published 1980); Wadsworth, Semantics and Pragmatics of the Lambda-Calculus (1971); de Bruijn, "Lambda calculus notation with nameless dummies" (1972); Girard, Interprétation fonctionnelle et élimination des coupures (1972); Reynolds, "Towards a theory of type structure" (1974) and "Types, abstraction and parametric polymorphism" (1983); Milner, "A theory of type polymorphism in programming" (1978); Damas & Milner, "Principal type-schemes for functional programs" (1982); Girard, "Linear logic" (1987); Coquand & Huet, "The calculus of constructions" (1988); Wadler, "Theorems for free!" (1989); Mairson, "Deciding ML typability is complete for deterministic exponential time" (1990); Kfoury, Tiuryn & Urzyczyn, "ML typability is DEXPTIME-complete" (1990); Griffin, "A formulae-as-types notion of control" (1990); Rémy, "Extending ML type system with a sorted equational theory" (1992); Wells, "Typability and type checking in the second-order λ-calculus are equivalent and undecidable" (1994); Kfoury & Wells, "A direct algorithm for type inference in the rank-2 fragment" (1994).
Recent. McAllester, "A logical algorithm for ML type inference" (2003); Siek & Taha, "Gradual typing for functional languages" (2006); Rondon, Kawaguchi & Jhala, "Liquid types" (2008); Plotkin & Pretnar, "Handlers of algebraic effects" (2009); Hoare, "Null references: the billion dollar mistake" (2009); The Univalent Foundations Program, Homotopy Type Theory (2013); Cohen, Coquand, Huber & Mörtberg, "Cubical type theory" (2015); Siek, Vitousek, Cimini & Boyland, "Refined criteria for gradual typing" (2015); Takikawa et al., "Is sound gradual typing dead?" (2016); Jung et al., "RustBelt: securing the foundations of the Rust programming language" (2018); Sivaramakrishnan et al., "Retrofitting effect handlers onto OCaml" (2021); Wadler, "Propositions as types" (2015).
About this partfrom its README
Part 14 of a sixty-one-part course in computer science (see the series plan and
the syllabus), in Act III, Speaking to the Machine. Church's λ-calculus is a whole programming
language made of functions alone; types tame it; well-typed programs cannot go wrong, which we prove and check; a
type can be inferred without being written; and types turn out to be propositions and programs to be proofs. The
instruments are Part 1's explainer/cs/lam.py (terms, substitution, normal order) and explainer/cs/lang/lam/:
reduce.py (five strategies, an environment machine with thunks that counts sharing, the whole reduction graph,
complete developments, de Bruijn indices, the Church encodings), stlc.py (the simply typed calculus with booleans
and naturals: derivations, small-step evaluation, a random generator, finite checks of the safety rules), ml.py (the
λ-core, a small ML with Hindley–Milner inference by Algorithm W with levels, an evaluator, and the Job written in
it) and logic.py (proof search as program search, truth tables, Kripke countermodels), tested in
tests/test_cs14_types.py. Every number is computed in compute.py; rustc and tsc on this machine supply
chapters 13 and 14's compiler messages.
- A language made of functions. The Job in the λ-core with not one annotation, and every type inferred
(
bump : 'a -> ('a * int) list -> ('a * int) list); 2 + 3 in pure λ, six β-steps to the numeral 5. - 1. Terms, variables and substitution. Three kinds of term and their trees; free and bound variables;
α-equivalence; the capture trap,
(λx. λy. x) y, and capture-avoiding substitution. - 2. Reduction and normal forms. β-reduction; a step that copies a redex; 2 + 3 redex by redex; Ω; a term with a normal form along one path and an infinite path along another.
- 3. Programming with nothing. Booleans as choices (and/or checked); numerals as repetition, drawn as nested boxes; plus, times and pow (6, 9 and 16 steps); pairs; Kleene's predecessor (9 steps at zero; 10n + 6 at positive n); lists as folds.
- 4. Recursion without names. Fixed points; Y unfolding; factorial through Y (24 for n = 4, in 10,384 steps); Y cannot return a closure under call-by-value; Z can, but strict factorial also needs delayed conditional branches. The repaired example computes 0! through 3! with actual CBV numeral readback.
- 5. Evaluation strategies. Normal, applicative, by name, by value, by need; K a Ω under each; sharing counted (43 against 33 β-steps when an argument is used three times); the standardization theorem.
- 6. Church–Rosser, and de Bruijn. The full reduction graph of a small term (6 terms, 7 steps, one normal form) and a bigger one (30 terms, 93 steps, confluent); the diamond and parallel reduction; de Bruijn indices.
- 7. Simple types. Stuck terms; Milner's slogan; the syntax and rules; a derivation tree drawn by our checker; a small-step trace with its rules.
- 8. Well-typed programs cannot go wrong. Progress and preservation; the proofs' key cases (canonical forms, the substitution lemma); both checked on 5,000 random terms and 50,516 steps; safety in real languages.
- 9. Strong normalization in the recursion-free simply typed core. Ω is untypable (
'a = 'a -> 'b); Tait's strong normalization and logical relations; 136 of 2,000 random untyped terms still running after 400 steps, none of 5,000 typed ones; the price, andfix. - 10. Hindley–Milner inference. Unification (Robinson 1965) and its occurs check; our engine's trace for
fun f x -> f (f x); let-polymorphism; the Job's eleven principal types; the nested-let worst case, 2^(2^n) leaves, DEXPTIME-complete. - 11. Polymorphism and free theorems. System F; Church's encodings typed; parametricity; the free theorem
map f ∘ g = g ∘ map ftested on four polymorphic functions (200/200 each) and broken by a monomorphic function. An additional equality-selector counterexample has the same printed polymorphic type in our toy core: unrestricted structural equality is outside pure System F parametricity. A commuting-square diagram shows the actual failure on [1,2] mapped to [0,0]. Real ML equality-type constraints need more modeling than this printer provides. - 12. Propositions as types. The dictionary; programs found by proof search (S, K, composition,
¬¬(A ∨ ¬A)); excluded middle, double negation, Peirce and de Morgan's half with no program; a two-world Kripke model; call/cc and Peirce's law (Griffin 1990). - 13. Dependent and linear types. Vectors indexed by length; Π and Σ; Martin-Löf, Coq/Rocq, Lean; linear, affine and relevant combinators; rustc's E0382 and E0502.
- 14. Data, subtyping and gradual types. Algebraic data types and
option; variance; TypeScript's covariant arrays accepted bytsc --strictand failing in node;any; Siek and Taha's gradual typing and its cost. - 15. Frontier: the edges of type theory. Single-host inference samples for 32 copies of eleven definitions (352 total), with a data-derived axis; refinement types and SMT; homotopy type theory, univalence and cubical type theory; effect handlers; open problems.
- Recap, where this comes back, in practice, problems.
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- λ-terms: three kinds of term and their trees; free and bound variables, α-equivalence; capture-avoiding substitution and the capture trap.
- β-reduction rewriting a subtree; normal forms; Ω = (λx.xx)(λx.xx).
- Church encodings: booleans, numerals as stacked function boxes, arithmetic measured in β-steps (plus, times, pow); pairs and lists; the predecessor (Kleene's trick, 9 + 10n steps).
- Recursion: the Y combinator derived; factorial by Y (1, 1, 2, 6, 24 in up to 10,384 steps); Y diverges under call-by-value and Z does not.
- Reduction strategies: normal order, applicative, call-by-name, call-by-value, call-by-need, compared on the same terms (β counts with sharing, 43/33/33 against 4/4/6); standardization.
- Church–Rosser: every reduction of a small term drawn as a graph (6 terms, 7 steps) and a larger one (30 terms, 93 steps, one normal form), confluence checked on the whole graph; the diamond, and why parallel reduction proves it; de Bruijn indices (environments against substitution, Part 15).
- Why types: Milner's slogan (1978); stuck terms; the simply typed λ-calculus with its rules as inference rules and derivation trees generated by our checker.
- Type safety = progress + preservation, proved by induction on derivations (canonical forms, the substitution lemma), then checked on 5,000 random well-typed terms (50,516 steps, none stuck, none changing type).
- Strong normalization (Tait 1967, logical relations sketched): Ω cannot be typed; 136 of 2,000 random untyped terms never stop, no typed one fails to; so STLC is not Turing-complete, and fix brings general recursion back.
- Hindley–Milner: algorithm W and unification (Robinson 1965), traced on the Job (11 types, 295 unifications); let-polymorphism; the occurs check; the exponential let (2^(2^n) leaves, cheap with sharing).
- System F (Girard 1972, Reynolds 1974); Church encodings typed; parametricity and a free theorem tested (Wadler 1989): four polymorphic functions hold 200/200, "add one" fails at once.
- Curry–Howard: implication, conjunction and disjunction as function, product and sum types; our prover searches for a λ-term and Kripke countermodels refute the rest (fifteen formulas); call/cc and Peirce's law (Griffin 1990).
- Dependent types: Vec, Π and Σ; Martin-Löf; the calculus of constructions; Agda, Lean and Rocq (Part 54); linear, affine and relevant combinators counted; Rust's ownership and borrowing, with rustc's E0382 and E0502 on this machine (Part 55).
- Algebraic data types and pattern matching; option instead of null; subtyping and variance; TypeScript's covariant arrays measured (tsc --strict accepts, node throws); gradual typing, sound and unsound (Siek and Taha 2006, Takikawa et al. 2016).
- Frontier: HM inference linear in practice and DEXPTIME-complete in theory (McAllester 2003); refinement types and SMT (liquid types, F*, Dafny); homotopy type theory and cubical univalence; effect handlers (Plotkin and Pretnar 2009, OCaml 5); open problems. Outro.
Computed: our λ reducer under four strategies and a lazy environment machine (β-step counts, Church arithmetic, reduction graphs, confluence checks); the STLC checker, its derivations and a random safety test; HM inference with traces and the exponential let; free theorems tested in the λ-core; a propositional prover with countermodels; rustc, tsc and node on this machine. Visuals: β-reduction rewriting a subtree; Church numerals as stacked function boxes; reduction graphs; the Church–Rosser diamond; derivation trees; unification merging type variables; the Curry–Howard dictionary. In practice: the type systems of TypeScript, Rust, Haskell, OCaml and Scala; generics; IDE type inference; gradual typing in large codebases; proof assistants. Reading: Pierce, Types and Programming Languages; Harper, Practical Foundations for Programming Languages; Barendregt, The Lambda Calculus; Hindley & Seldin; Sørensen & Urzyczyn, Lectures on the Curry–Howard Isomorphism; Girard, Lafont & Taylor, Proofs and Types; Wadler 1989, 2015; Milner 1978; Damas & Milner 1982; Siek & Taha 2006; Jung et al. 2018.
中文讲义
本讲的中文部分(与英文版对应)。
习题与解答
-
两种顺序。 分别用正规序和应用序把
(λx y. y x x) ((λz. z) a) (λw. w)归约到范式,数出步数,并解释差别。解答
正规序(5 步):把尚未归约的实参
(λz. z) a代入 x,得到(λy. y A A) (λw. w),其中 A =(λz. z) a; 然后是(λw. w) A A,再到A A,再分别归约 A 的两个副本:a A、a a。应用序(4 步):先把 A 归约成a, 然后(λx y. y x x) a→λy. y a a,再作用于恒等函数,(λw. w) a a→a a。正规序在求值之前复制了实参, 所以求值了两次;应用序只求值一次。两者到达同一个范式,正如丘奇–罗瑟定理所保证的。(我们的归约器reduce.run给出 5 和 4。) -
带代价模型的算术。 定义丘奇幂、零测试和饱和减法。采用每次求前驱后先完全正规化结果的算法,统计 β 收缩,说明为何不能笼统声称运行时间为 Theta(m*n)。
解答
exp = λm n. n m,iszero = λn. n (λz. false) true,sub = λm n. n pred m,结果是 max(m−n,0)。本库的完全正规序前驱计数为 p(0)=9,正数时 p(k)=10k+6。每次先正规化中间数,计数是对 i=0..n−1 求和 p(max(m−i,0))。令 r=min(m,n),得到 r(10m+6)−5r(r−1)+9(n−r)。对非平凡输入,这一特定收缩计数算法的阶是 n+m*min(m,n),包含归零后的饱和行为。再加上字面sub项外层的四次收缩,与本次 63 组 (m,n) 样本一致,但有限一致不证明所有归约器的普遍复杂度。n=0 时四次收缩就返回已有数;输出 m 次应用、复制语法和分配内存另有代价。比较实现前应明确表示、停止标准、共享与单位代价。 -
进展性的两个情形。 证明 If 和 Succ 两种情形下的进展性,并写出所需的典范形式引理。
解答
典范形式:Bool 类型的值是 true 或 false;Nat 类型的值是 0 或 succ v(v 是数值);A → B 类型的值是一个 λ。If 情形:⊢ if c a b : T 需要 ⊢ c : Bool。由归纳假设,c 是值或能走一步。若能走一步,E-If 使整个项走一步。若是 值,由典范形式它是 true 或 false,于是 E-IfTrue 或 E-IfFalse 适用。Succ 情形:⊢ succ t : Nat 需要 ⊢ t : Nat。 若 t 能走一步,succ t 也能(E-Succ);若 t 是值,由典范形式它是数值,于是 succ t 本身就是值。
-
手工推断。 推断
λf g x. g (f x) x的主类型,写出每一次合一。解答
设 f : α,g : β,x : γ。
f x迫使 α = γ → δ。g (f x)迫使 β = δ → ε。(g (f x)) x迫使 ε = γ → ζ。代入后:f : γ → δ,g : δ → γ → ζ,x : γ,结果为 ζ。改名之后,主类型是('a -> 'b) -> ('b -> 'a -> 'c) -> 'a -> 'c,与我们的引擎报告的完全一致,三次绑定的顺序也相同。 -
构建范围明确的 option 类型。 加入
'a option = None | Some of 'a,先只允许构造子后接互异变量的浅层模式。支持类型推断,并让任务的查找返回 option。解答
None的方案为 forall a. a option,Some为 forall a. a -> a option,每次使用重新实例化。匹配时,把被匹配值与 option tau 合一,给 Some 的字段绑定 tau,并合一各分支结果。这个浅层片段中,None 与 Some 均出现,或最后的通配分支覆盖余项,即为穷尽;重复分支应拒绝或报告不可达。仅数顶层构造子,不能判断Some (Some x)等嵌套模式是否穷尽;扩展需要递归的模式矩阵专化与默认情形。求值使用带标签的值。实现find : 'a -> ('a * 'b) list -> ('a * 'b) option后,用空输入、重复词、同频词和缺失键,对照job_reference。真实 ML 还须明确处理相等约束,本玩具打印器没有显示它们。这是构建规格,不表示仓库已经实现用户自定义 ADT。 -
★ 研究:空间高效的渐进检查。 为一个小型高阶渐进演算复现已知的强制组合方案,再定义一个扩展并调查。
从哪里开始。 明确有类型与无类型边界的语义、可观察错误、基准程序及代价模型。直接使用包装链可能积累代理,但已有空间高效强制通过组合检查阻止这种增长;提出下界之前,先复现该结果。分别跟踪最大存活强制大小、分配次数、检查次数与运行时间。然后选择例如具有明确语义的可变引用扩展,调查已知结果后再主张新颖性。2016 年 Typed Racket 研究在部分被测配置中观察到超过 100 倍开销;这是历史负载结果,不是普遍下界。表示的空间上界也不等于运行时间具有普遍常数开销因子。可从 2006 年渐进类型、2015 年细化判据、Grift(2019)以及 ECOOP 2020 的强制传递风格空间高效渐进类型工作开始。
Build the film
python -m videos.cs.cs14.compute # the part's numbers, into .cache/cs14
python tools/build.py cs14 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py cs14 Hook # one chapter, silent, with a contact sheet
Scenes: videos/cs/cs14. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
python -m videos.cs.cs14.compute # compute missing items; timings depend on this host
python tools/build.py cs14 -q l # a 480p preview
python tools/build.py cs14 # 1080p
The rust and gradual items call rustc and tsc/node on this machine and record their versions; the
frontier timings belong to the computer that runs them. Finite random samples check implementations; they do not prove general theorems. Beta-step counts describe this encoding and evaluator, excluding syntax-copy, allocation and machine-time costs. RustBelt verifies a realistic subset and selected unsafe abstractions, not every Rust implementation. Strong normalization and parametricity claims retain their pure-core assumptions; explicit System F checking differs from unrestricted implicit inference.