2. Types

Draft

A paradox and a remedy

In the untyped calculus of Section 1, any term may be applied to any term, itself included. Self-application is both the source of its universal power, supplying the fixed points behind general recursion (Section 1.3), and the source of its breakdowns: endless loops like \(\Omega = (\lambda x.\, x\,x)\,(\lambda x.\, x\,x)\) in computation, and outright contradiction in the foundation of logic that the calculus was invented to carry. A type tames that freedom by attaching a static label to each term specifying what inputs it accepts and what output comes back: \(A \to B\) marks a function that takes an \(A\) and returns a \(B\). That label is a promise about a program, and a machine can check it from syntax alone without running the program. This part examines what that promise buys and what it costs: in every calculus treated here, a program that keeps the promise halts, and any language in which every program halts must omit some total computable functions, starting with its own evaluator. Within the series, types complete the computational side of turning proofs into objects that simplify to an end: Section 4 reads a type as a proposition and a term of that type as its proof.

Because a proof checker compares terms by reducing them, Section 1's undecidability theorem left open how a checker could reduce terms safely without risking an infinite loop. For the typed terms of this part, every reduction ends (Section 2.4), provided the type can be verified before running the term; the rules for checking explicit types and inferring omitted ones therefore come first (Sections 2.2 and 2.3). Halting exacts an expressive price (Section 2.5), and a three-dimensional map of type systems leads from these calculi directly to Lean's logic (Section 2.6).

term    λx:A → A. λy:A. x (x y)        the Church numeral 2 at the type A

tree    the derivation, the conclusion first, the premises of a judgment indented under it       rule
        ⊢ λx:A → A. λy:A. x (x y) : (A → A) → A → A                                              abs
          x:A → A ⊢ λy:A. x (x y) : A → A                                                        abs
            x:A → A, y:A ⊢ x (x y) : A                                                           app
              x:A → A, y:A ⊢ x : A → A                                                           var
              x:A → A, y:A ⊢ x y : A                                                             app
                x:A → A, y:A ⊢ x : A → A                                                         var
                x:A → A, y:A ⊢ y : A                                                             var

rules   var   Γ, x:A ⊢ x : A
        app   from Γ ⊢ M : A → B and Γ ⊢ N : A infer Γ ⊢ M N : B
        abs   from Γ, x:A ⊢ M : B infer Γ ⊢ λx:A. M : A → B

7 judgments, one for each subterm, one rule each (var 3, app 2, abs 2), found in 11 steps of the checker.
Lean 4.35.0 prints for the same term: fun x y => x (x y) : (A → A) → A → A
The term λx:A. x x stops at x x: the function has type A, which is not an arrow.
(the live figure needs JavaScript; it loads no data)
A term with a type written at every λ, and the tree of its typing judgments. Green: the judgment being derived. A judgment appears in grey, its type a question mark, when the rule under it is read upward, and turns to ink when its type has been computed from its premises; each line carries its rule's name. Step through the checker, point at a judgment, choose a term or type one. A term without a type stops at a framed judgment that no rule derives. Computed in the page; the readout gives what Lean 4.35.0 printed for the same term.

Self-application is what the checker refuses, and the check fails right at \(x\,x\). Whatever type \(A\) is written on \(\lambda x{:}A\), the rule for an application requires the \(x\) in function position to have an arrow type \(A \to B\) so it can accept the argument \(x : A\), yet no finite type expression \(A\) equals an arrow \(A \to B\) beginning with itself. So \(x\,x\) cannot be typed, banishing \(\Omega\) and every fixed-point combinator of Section 1.3 at one stroke.

The remedy is older than the calculus and was made for the same disease. Around 1901 Russell asked whether the class of all classes that are not members of themselves is a member of itself, and found that it is if and only if it is not; what the question did to Frege, and to the foundations of mathematics, is told in The painted rock. In the notation of Section 1 the paradox is a self-application. Write \(N\) for negation and \(R = \lambda x.\, N\,(x\,x)\) for the property of not holding of oneself. Then

\[R\,R \;\to_\beta\; N\,(R\,R),\]

a proposition that computes to its own negation. Church's first paper on the calculus, in 1932, writes the paradox with this term, and with a variable \(f\) in place of \(N\) it becomes \((\lambda x.\, f\,(x\,x))\,(\lambda x.\, f\,(x\,x))\), a fixed point of \(f\): the recursion of Section 1.3 and Russell's paradox are one construction.F. Cardone and J. R. Hindley, "History of lambda-calculus and combinatory logic", Swansea University Mathematics Department Research Report MRRS-05-06 (2006), Section 4.1, pp. 8–9: the accounts of Russell's paradox in Church's paper of 1932 and in a paper of Curry's of 1934 both use \((\lambda y.\, N\,(y\,y))\,(\lambda y.\, N\,(y\,y))\), with \(N\) for negation. The date is that of the Stanford Encyclopedia of Philosophy ("Russell's Paradox", revision of 13 March 2026): the paradox was discovered "in or around 1901".

Russell's own answer, first proposed in 1903, is worked out in a paper of 1908. It lists seven contradictions, the liar and the greatest ordinal among them, finds in all of them "self-reference or reflexiveness", draws the rule "Whatever involves all of a collection must not be one of the collection", and then says what a type is.

A type is defined as the range of significance of a propositional function, i.e., as the collection of arguments for which the said function has values. Whenever an apparent variable occurs in a proposition, the range of values of the apparent variable is a type, the type being fixed by the function of which "all values" are concerned. The division of objects into types is necessitated by the reflexive fallacies which otherwise arise. These fallacies, as we saw, are to be avoided by what may be called the "vicious-circle principle;" i.e., "no totality can contain members defined in terms of itself." This principle, in our technical language, becomes: "Whatever contains an apparent variable must not be a possible value of that variable." Thus whatever contains an apparent variable must be of a different type from the possible values of that variable; we will say that it is of a higher type. Thus the apparent variables contained in an expression are what determines its type. This is the guiding principle in what follows.

—Bertrand Russell, "Mathematical logic as based on the theory of types" (1908). American Journal of Mathematics 30(3), pp. 222–262; the passage is in Section IV, "The Hierarchy of Types", pp. 236–237. An apparent variable is a bound variable, and a propositional function is a predicate. The seven contradictions are on pp. 222–224 and the rule on p. 225. Two footnotes cite an essay of Poincaré's of May 1906: one on p. 223, to Richard's paradox, the sixth of the contradictions, and one on p. 236, to the suggestion that one may speak of all of a collection only when the collection is finite.

Russell's first sentence gives the notion of type still in everyday use: a function comes with the collection of arguments on which applying it makes sense. The vicious-circle principle in the middle of the passage demands something much stricter, and keeping those two ideas apart clarifies everything that follows.

Remark 2.1.1 (two hierarchies). Russell's 1908 hierarchy bundles two distinct restrictions together. Grading expressions solely by what a function takes and returns (individuals at level 0, functions of individuals at level 1, functions of those at level 2, and so on) already blocks applying a thing to itself: this is the simple theory of types. Grading expressions further into orders according to the quantifiers inside their definitions, so that anything defined by quantifying over a totality stands at a higher order than the members of that totality, enforces the vicious-circle principle: this is the ramified theory of types. Ordinary mathematics violates that second restriction daily. When analysis singles out the least upper bound of a nonempty bounded set of real numbers as the smallest of all its upper bounds, the quantifier ranges over a collection to which the least upper bound itself belongs; a definition of this kind is called impredicative. Poincaré, whom Russell cites, held that "A definition containing a vicious circle defines nothing", and the ramified theory takes him at his word, with the crippling consequence that "all basic mathematical notions, like real or natural numbers are stratified into different orders". Russell added an Axiom of Reducibility to undo that stratification, and in the 1920s Chwistek and Ramsey observed that once reducibility is assumed "there is actually no point in introducing the ramified hierarchy at all". Modern type theory kept the simple hierarchy and kept impredicative definitions with it. The simply typed lambda calculus enforces only the simple hierarchy: it forbids \(x\,x\), and has no quantifiers over types yet. When quantifiers over all types or all propositions return, in System F (Section 2.5) and in Lean's Prop universe (Section 5.7), impredicativity returns with them on purpose.The two sentences on the ramified hierarchy are from T. Coquand, "Type Theory", Stanford Encyclopedia of Philosophy (substantive revision of 20 November 2026), Section 3. Poincaré: Science et méthode (1908), book II, chapter V, in G. B. Halsted's translation, The Foundations of Science (1913), pp. 481–482; the class at issue there is that of the inductive numbers, and of a class so defined the same paragraph says that it "is not an empty class, it is a class whose boundary is undetermined".

Next come the exact rules of the simply typed lambda calculus.

The simply typed lambda calculus

Once the untyped logic was proved inconsistent in 1935, Church, in the words of the calculus's historians, "retreated from the task of designing a general type-free logic to the much less ambitious one of re-formulating simple type theory on a λ-calculus base".Cardone and Hindley (2006), Section 4.1, p. 9. Church lectured on the system at Princeton in 1937–38, with Turing in the audience (Section 5.1, p. 12). His 1940 paper introduced the simply typed calculus whose derivation trees Section 2.1 drew. In the browser's checker, the entire typing discipline fits into a single recursive switch with one branch for each kind of term.

switch (t.k) {
  case 'var': { const ty = lookup(G, t.name); if (ty) node.type = ty; else fail(node, 'the variable ' + t.name + ' is not in the context'); break; }
  case 'lam': {
    const A = t.type || (want && want.k === 'arrow' ? want.from : null);
    if (!A) { fail(node, 'the variable ' + t.name + ' needs a type'); break; }
    const b = kid(t.body, G.concat([[t.name, A]]), 0, want && want.k === 'arrow' ? want.to : undefined);
    if (b.ok) node.type = Ty.arrow(A, b.type);
    break;
  }
  case 'app': {
    const f = kid(t.fn, G, 0), a = kid(t.arg, G, 1, f.type && f.type.k === 'arrow' ? f.type.from : undefined);
    if (!node.ok) break;
    if (f.type.k !== 'arrow') fail(node, 'the function has type ' + show(f.type) + ', which is not an arrow');
    else if (!Ty.eq(a.type, f.type.from)) fail(node, 'the function takes ' + show(f.type.from) + ', the argument has type ' + show(a.type), { expected: f.type.from, found: a.type });
    else node.type = f.type.to;
    break;
  }
  // ...

Here G is the typing context (the variables currently in scope paired with their declared types), kid checks a subterm recursively and hangs its child judgment under the current one, and want carries an optional expected type from outside when a binder carries none. Nothing in these lines backtracks, searches, or guesses. On a closed term (one with no free variables) carrying a type at every binder, the two error messages inside app are the only possible failures.

Proving mathematical theorems about what this checker accepts requires stating the grammar of types and the typing rules independently of the JavaScript code. Simple types start from atomic base types and build function types with a single arrow constructor.

Definition 2.2.1 (simple types). Fix a set of base types, written \(o\) or by a name. The simple types are the base types and, for simple types \(A\) and \(B\), the function type \(A \to B\). The arrow associates to the right: \(A \to B \to C\) is \(A \to (B \to C)\), the type of a function of two arguments that takes them one at a time.

Notice how right-associative arrows mirror left-associative application: applying \(M : A \to (B \to C)\) to \(N : A\) produces \(M\,N : B \to C\), which then accepts \(P : B\) to produce \((M\,N)\,P : C\). Three inference rules now mirror the three branches of the switch, one rule for each kind of term; erasing the terms from these rules leaves the exact logical rules for proving implications (Section 4.1).

Definition 2.2.2 (typed terms and judgments). A term is a variable \(x\), an application \(M\,N\) or an abstraction \(\lambda x{:}A.\, M\), which is the abstraction of Section 1.1 with the type of its variable written in. A context \(\Gamma\) is a finite list \(x_1 : A_1, \dots, x_n : A_n\) of distinct variables with types, in which the order does not matter. The judgment \(\Gamma \vdash M : A\) says that \(M\) has the type \(A\) when its free variables have the types listed in \(\Gamma\). Judgments are derived by three rules, the premises above the line and the conclusion under it:

\[\frac{}{\;\Gamma,\, x : A \vdash x : A\;}\;(\text{var}) \qquad \frac{\Gamma \vdash M : A \to B \qquad \Gamma \vdash N : A}{\Gamma \vdash M\,N : B}\;(\text{app}) \qquad \frac{\Gamma,\, x : A \vdash M : B}{\Gamma \vdash \lambda x{:}A.\, M : A \to B}\;(\text{abs})\]

In the rule (abs) the bound variable is renamed if \(\Gamma\) already has an \(x\). A derivation is a tree of judgments, each obtained from those over it by a rule, and a term is typable in \(\Gamma\) if some judgment \(\Gamma \vdash M : A\) has a derivation.The rules as P. Selinger sets them out, "Lecture notes on the lambda calculus" (arXiv:0804.3434, 2013), Section 6.1, Table 4, with the remark that "there is precisely one rule for each kind of lambda term". Subject reduction is his Theorem 6.1, stated there for beta and eta steps.

In general formal systems, testing whether a statement is derivable can require searching through infinitely many candidate trees. Because Church-style terms write the input type \(A\) onto every \(\lambda x{:}A\), these three rules are syntax-directed: the outermost constructor of \(M\) leaves only one rule to try.

Proposition 2.2.3 (the type is read off the term). In a given context a term has at most one type, and a typable term has exactly one derivation, with one judgment for each of its subterms.

Proof. By induction on the term. Each kind of term is the conclusion of exactly one rule, whose premises are judgments about its immediate subterms in contexts that the conclusion determines. In (var) the type is the one the context lists; in (abs) \(A\) is written in the term and \(B\) is unique by induction; in (app) the type of \(M\) is unique by induction, and it fixes \(B\). ∎

Syntax-directed uniqueness is why a type checker computes deterministically and never searches, in Lean's kernel just as here (Section 6.2). It also turns the informal rejection of \(x\,x\) from Section 2.1 into a short proof covering every possible annotation at once.

Example 2.2.4 (self-application has no type). Suppose \(\Gamma \vdash x\,x : B\). Only (app) derives an application, so \(\Gamma \vdash x : A \to B\) and \(\Gamma \vdash x : A\) for some type \(A\); since \(\Gamma\) lists a single type for \(x\), Proposition 2.2.3 forces \(A = A \to B\), which no finite type satisfies because \(A \to B\) has strictly more symbols than \(A\). Because every subterm of a typable term must also be typable, no term containing \(x\,x\) has a type under any binder annotations: not \(\lambda x{:}A.\, x\,x\), not \(\Omega\), and none of the fixed-point combinators of Section 1.3. ◁

Checking \(\Gamma \vdash M : A\) inspects \(M\) statically before a single reduction step runs. For that static check to guarantee anything about evaluation, β-reduction must never alter or break a term's type.

Theorem 2.2.5 (subject reduction). If \(\Gamma \vdash M : A\) and \(M \to_\beta M^{\prime}\), one step of the beta rule of Section 1.1, then \(\Gamma \vdash M^{\prime} : A\).

Proving Theorem 2.2.5 by induction on the typing derivation rests on one substitution lemma: whenever \(\Gamma, x : A \vdash M : B\) and \(\Gamma \vdash N : A\), substituting \(N\) for \(x\) inside \(M\) yields \(\Gamma \vdash M[x := N] : B\), so contracting \((\lambda x{:}A.\, M)\,N \to_\beta M[x := N]\) preserves type \(B\). Subject reduction makes the static promise exact: apply any closed function of type \(A \to B\) to any closed argument of type \(A\), and the expression has type \(B\) initially and keeps type \(B\) through every step of reduction. Section 2.4 adds the second half of the promise, proving that the reduction ends.

Church's paper opens with what had to be given up.

The purpose of the present paper is to give a formulation of the simple theory of types which incorporates certain features of the calculus of λ-conversion. A complete incorporation of the calculus of λ-conversion into the theory of types is impossible if we require that λx and juxtaposition shall retain their respective meanings as an abstraction operator and as denoting the application of function to argument. But the present partial incorporation has certain advantages from the point of view of type theory and is offered as being of interest on this basis (whatever may be thought of the finally satisfactory character of the theory of types as a foundation for logic and mathematics).

—Alonzo Church, "A formulation of the simple theory of types" (1940). Journal of Symbolic Logic 5(2), pp. 56–68; the first paragraph of the paper. The publisher's page prints its first three paragraphs, and only they are drawn on here. The third defines the types as "the least class of symbols which contains the symbols ı and o and is closed under the operation of forming the symbol (αβ) from the symbols α and β". By the Stanford Encyclopedia's entry "Church's Type Theory" (revision of 16 January 2024, Section 1.2.1), ι is the type of individuals, o that of truth values, and (αβ), against the order one would guess, the type of functions from β to α.

In Lean 4.35.0, the #check command computes and prints typing judgments of this exact form, and the expressions inside Lean's kernel store an explicit binder type just as Church's annotated terms do: in Lean's source code, Expr.lam carries a binderType field (Section 6). Section 2.7 tests the terms of this section in Lean.

Writing an explicit type on every \(\lambda\) keeps a kernel tiny and deterministic, while quickly growing tedious for human authors to type by hand.

Inference: a type as the solution of equations

In the simply typed calculus, binder annotations can be omitted from user input because an algorithm can reconstruct them automatically. Erase every : A from a typed term and what remains is an unannotated ("bare") term of Section 1; type inference asks whether valid binder types can be restored, and whether a single most general type captures all valid ways of doing so.

term       λx y. y (λz. y x)             no type is written; one is to be found

unknowns   λx : α     λy : β     λz : γ     y x : δ     y (λz. y x) : ε
equations  from y x            β = α → δ
           from y (λz. y x)    β = (γ → δ) → ε

step   action      the equation solved       the unknowns after it
1      bind        β = α → δ                 β := α → δ
2      decompose   α → δ = (γ → δ) → ε       splits into α = γ → δ and δ = ε
3      bind        α = γ → δ                 β := (γ → δ) → δ    α := γ → δ
4      bind        δ = ε                     β := (γ → ε) → ε    α := γ → ε    δ := ε

the principal type   λx y. y (λz. y x) : (γ → ε) → ((γ → ε) → ε) → ε
an instance of it    ⊢ λx:A → B. λy:(A → B) → B. y (λz:A. y x) : (A → B) → ((A → B) → B) → B
no type              λx. x x gives α = α → β, unfolded α = α → β = (α → β) → β = ((α → β) → β) → β = …

5 unknowns, 2 equations, solved in 4 steps (3 bind, 1 decompose).
Lean 4.35.0 accepts the term when this type is written, and does not find it for the bare term
(#check answers: Function expected at y but this term has type ?m.5 x).
(the live figure needs JavaScript; it loads no data)
The type of a term written without types, found by solving equations. Every binder and every application gets an unknown type; every application gives one equation. Green: the equation being solved. Washed: the values the step changed. A step binds a variable, splits an equation between two arrows, or drops a trivial one; an equation that asks a variable to contain itself is framed, and the term has no type. Under the tables stands the type of the whole term so far. Step, choose a term or type one. Inferred in the page; the readout says what Lean 4.35.0 does with the same term.

Typing a bare term reduces to solving algebraic equations between type expressions. Assign a fresh unknown type variable (\(\alpha, \beta, \gamma, \dots\)) to each binder and to the result of each application; then every application \(M\,N\) contributes one equation requiring the type of \(M\) to equal the arrow from the type of \(N\) to the type of \(M\,N\). A solver either returns the most general solution of those equations or isolates an impossible circular equation. Among all 201 closed bare terms of at most seven nodes (counting variables, abstractions, and applications as one node each), 148 are typable, and all 53 untypable terms fail at the exact same obstacle: an equation asking an unknown to contain itself properly, just as \(\alpha = \alpha \to \beta\) does for \(\lambda x.\, x\,x\).

Because an unannotated term like \(\lambda x.\, x\) admits infinitely many concrete types (\(A \to A\) for every \(A\)), "most general" needs a formal definition.

Definition 2.3.1 (type assignment and principal types). In type assignment the terms are the bare terms of Section 1, and the rule (abs) reads: from \(\Gamma, x : A \vdash M : B\) infer \(\Gamma \vdash \lambda x.\, M : A \to B\). The other two rules are unchanged. Let types now contain type variables \(\alpha, \beta, \dots\), and call a substitution any replacement of type variables by types. A type \(A\) of a closed term \(M\) is principal if every type of \(M\) is obtained from \(A\) by a substitution.

For \(\lambda x.\, x\), the type \(\alpha \to \alpha\) is principal because every valid type \(A \to A\) comes from substituting \(A\) for \(\alpha\). Every typable bare term possesses a principal type, and four elementary equation-solving steps suffice to compute it.

Theorem 2.3.2 (principal types). There is an algorithm that, given a closed bare term, returns a principal type of it or reports that it has no type. Give every binder and every application an unknown, a type variable of its own; for each application \(M\,N\) write the equation between the type of \(M\) and the arrow from the type of \(N\) to the type of \(M\,N\); then repeat, on the first equation left, whichever of four actions applies:

  • the two sides are the same type: drop the equation;
  • one side is a variable \(\alpha\) that does not occur in the other side \(A\): put \(A\) for \(\alpha\) everywhere;
  • one side is a variable \(\alpha\) that occurs in the other side, which is not \(\alpha\) itself: stop, the term has no type (the occurs check);
  • both sides are arrows, \(A_1 \to A_2 = B_1 \to B_2\): replace the equation by \(A_1 = B_1\) and \(A_2 = B_2\).

The procedure always ends, and if it is not stopped, the type it has found for the whole term is principal.H. Geuvers, "Introduction to type theory" (notes of the Alpha Lernet summer school, Piriápolis, 2008), Definition 19 and Theorem 5. The procedure is the one of these notes: the five steps before their Example 10, and the unification of their Definition 18, which looks at the first equation left. Selinger's notes (Sections 9.3 to 9.5) unify while they walk the term; writing all the equations first is the method that Curry and Feys described informally in 1958. Unification is J. A. Robinson's algorithm of 1965. Hindley used it to compute principal types (for combinatory logic, 1967, printed 1969); Morris (1968) and Milner (1978) each came to an algorithm for principal types independently (Cardone and Hindley, Section 8.5, pp. 42–43).

Why it works. This equation-solving procedure is J. A. Robinson's unification algorithm: it finds a most general substitution of types for type variables that makes both sides of every equation syntactically identical. Termination holds because the second action eliminates one variable \(\alpha\) across all remaining equations forever, while the first and fourth actions discard or decompose equations without introducing new variables. Principal generality holds because each non-failing action replaces the system with an equivalent set of equations sharing the exact same set of valid substitutions. Finally, the occurs check in the third action catches genuine impossibility: under any substitution, \(\alpha\) would remain strictly shorter than an arrow expression properly containing \(\alpha\).

Explicitly annotated terms (Church style, 1940) and implicit type assignment on bare terms (Curry style, 1934) therefore describe the exact same typable programs: erasing the binder types from any Church-style term yields a valid type of the bare term, and conversely every Curry-style type of a bare term comes from a valid Church-style annotation.Geuvers's notes, Definitions 14 to 16 and Theorem 3. The styles are named after their founders: Church's system of 1940 writes the types into the terms, and Curry's theory of functionality, in papers of 1934 and 1936, assigns types to untyped combinators (Cardone and Hindley, Section 4.2, p. 9).

One calculus, typed two waysa row to a question; left, terms that carry their types; right, terms that are assigned them

  1. the term

    types in the term Every bound variable carries its type: λx:A. x. The type is part of what is written.

    bare terms The terms of Section 1 with nothing added: λx. x. Types are assigned to them from outside.

    2.2
  2. the types of a term

    one, or none In a given context a term has at most one type, and its derivation is read off the term.

    none, or infinitely many λx. x has the type A → A for every A. All the types of a term are instances of one, its principal type.

    2.3
  3. what a machine does

    checks Applies the one rule for each kind of term and computes the types on the way back. Nothing is searched.

    infers Gives every binder and every application an unknown, writes one equation for each application, and solves them.

    2.3
  4. in Lean

    what the kernel receives Terms in which every binder has its type: the abstraction of Lean's kernel stores it.

    what a person types The source leaves types and arguments out, and the elaborator solves for them by unification before the kernel sees the term.

    2.7

Types came out of the paradoxes and entered the lambda calculus as a logic. Seventy years after Russell's paper the algorithm reached programmers, in a paper whose abstract states in two theorems what a type buys.

The aim of this work is largely a practical one. A widely employed style of programming, particularly in structure-processing languages which impose no discipline of types, entails defining procedures which work well on objects of a wide variety. We present a formal type discipline for such polymorphic procedures in the context of a simple programming language, and a compile time type-checking algorithm W which enforces the discipline. A Semantic Soundness Theorem (based on a formal semantics for the language) states that well-type programs cannot “go wrong” and a Syntactic Soundness Theorem states that if W accepts a program then it is well typed. We also discuss extending these results to richer languages; a type-checking algorithm based on W is in fact already implemented and working, for the metalanguage ML in the Edinburgh LCF system.

—Robin Milner, "A theory of type polymorphism in programming" (1978). Journal of Computer and System Sciences 17, pp. 348–375, the abstract; "well-type programs" is the print's wording. LCF is a proof checker, named after the logic of computable functions that it implemented, and ML is, in the abstract's word, its metalanguage; by the paper's account the type checker had then been in use "for nearly 2 years".

Milner's Semantic Soundness says that the type's promise is kept at runtime; Syntactic Soundness says that the inference algorithm can be trusted.

Because full type inference without annotations becomes undecidable once types are rich enough to express mathematics (Sections 2.5 and 2.6), Lean does not run Hindley-Milner inference on an unannotated fun. Asked for the type of fun f x => f x with no surrounding context, Lean stops at f, refusing to guess that f's unknown type is an arrow; given an expected type, Lean checks the term immediately. Where Lean does solve equations by unification is on omitted implicit arguments (Section 2.7), a core mechanism inside the elaborator that turns concise user syntax into fully annotated Church-style terms for the kernel (Section 9).

Subject reduction promises what type a result will have if evaluation finishes; next comes the proof that evaluation always finishes.

Typed terms halt, and how long they may take

In the untyped calculus, terms like \(\Omega\) have no normal form and terms like \(\mathsf{K}\,\mathsf{I}\,\Omega\) halt under normal order while looping under applicative order (Section 1.4). Attaching simple types transforms the reduction graph completely: draw every reachable reduct of a well-typed term, and every step points strictly downward with no cycles anywhere.

graph   every reduct of 2 2 (the Church numeral 2 applied to itself): 12 terms, 16 beta steps between them,
        no cycle, one normal form (the numeral 4); the longest path takes 6 steps, the shortest 5
        2 3: 30 reducts, longest path 8        3 2: 412 reducts, longest path 14
        2 2 2: more than 20,000 reducts, counted, not drawn

rows    term         value      nodes of the normal form       beta steps, innermost    leftmost-outermost
        2            2          7                              0                        0
        2 2          4          11                             5                        6
        2 2 2        16         35                             16                       42
        2 2 2 2      65,536     131,075                        63                       192,756
        2 2 2 2 2    2^65536    2^65537 + 3 (19,729 digits)    not run                  not run
        and eight terms of twos and threes, their normal forms from 19 to 39,369 nodes

steps are counts, not work: on 2 2 2 2 the 63 steps add 2,080 nodes to the term each on average and the
192,756 add 0.68; the two runs took 62 and 76 ms on the series' machine (medians of five), about the same time

Lean 4.35.0, each two at its own type, applied to Nat.succ and 0: #reduce gives 4 and 16; at four twos it
stops (maximum recursion depth has been reached); #eval answers 65536.
(the live figure needs JavaScript; it loads no data and counts for about a second)
Left, every reduct of a typed term: a dot to a term, an edge to a beta step, each term in the row of the longest way to it, so every step goes down to the one normal form (the square). Green: the longest path; the stepper walks it. Right, thirteen typed terms on a logarithmic scale: nodes of the normal form (square), beta steps leftmost-outermost (dot) and innermost (hollow dot), green where the whole graph was built. Steps are counts, not work: the two runs of four twos are timed in the page. The fifth tower leaves the canvas. The readout adds Lean 4.35.0's answer.

A simply typed term can never enter an infinite loop, resolving the undecidability impasse of Theorem 1.5.2: no algorithm can decide whether an untyped term has a normal form, whereas for a simply typed term the question is settled in advance by its type.

Theorem 2.4.1 (strong normalization). Every typable term of the simply typed lambda calculus is strongly normalizing: no infinite sequence of reductions \(M \to_\beta M_1 \to_\beta M_2 \to_\beta \cdots\) starts from it. With the Church-Rosser theorem of Section 1.4 it follows that a typed term has exactly one normal form, and that every way of reducing it reaches that normal form within a number of steps that depends only on the term.Selinger's notes, Theorems 7.1 and 7.2. That some reduction of a typed term ends was first proved by Turing, in a note "known to have been composed before 1942" and printed in 1980 (Cardone and Hindley, Section 8.2, p. 35). The method sketched here is W. W. Tait's ("Intensional interpretations of functionals of finite type", Journal of Symbolic Logic 32, 1967, pp. 198–212), as presented in chapter 6 of J.-Y. Girard, Y. Lafont and P. Taylor, Proofs and Types (1989); the bound on the number of steps is their Section 4.4.

One immediate payoff is that conversion \(=_\beta\) on simply typed terms is decidable: reduce both expressions to their unique normal forms along any convenient strategy and compare the results. That reduce-and-compare test is the prototype of how Lean's kernel decides definitional equality (Section 6.3), though Theorem 2.4.1 applies to the simply typed calculus; Section 6.6 states what is proved for Lean's full logic.

The idea of the proof. Why does a direct induction on the syntax of \(M\) fail? Variables and \(\lambda\)-abstractions go through easily, and then the induction hits application \(M\,N\): knowing that \(M\) and \(N\) each halt on their own says nothing about whether \(M\,N\) halts, because substituting \(N\) into the body of \(M\) can create brand-new redexes whenever \(N\) lands in function position (in the untyped calculus, \(\lambda x.\, x\,x\) is already in normal form, yet applying it to itself produces \(\Omega\)). For a function \(M : A \to B\), the induction hypothesis must carry a hereditary behavioral guarantee about what \(M\) does when applied to well-behaved inputs. William Tait built that stronger property by defining the reducible terms of each type \(T\) by recursion on the structure of the type \(T\) rather than the term: at a base type, a typed term is reducible if and only if it is strongly normalizing; at an arrow type \(A \to B\), a typed term \(M : A \to B\) is reducible if and only if \(M\,N\) is reducible at type \(B\) for every reducible argument \(N : A\). That definition makes the application step immediate and shifts the work to three closure properties proved simultaneously by induction on \(T\): every reducible term is strongly normalizing; reducibility is preserved under β-reduction; and any non-abstraction (such as a variable or a redex \((\lambda x{:}A.\, P)\,N\)) is reducible as soon as all of its one-step reducts are reducible, which makes bare variables reducible immediately (they have zero one-step reducts) and lifts reducibility from \(P[x := N]\) back to \((\lambda x{:}A.\, P)\,N\). A second induction on the syntax of any well-typed term \(M\) then shows that substituting reducible terms for all free variables of \(M\) yields a reducible term; substituting each free variable for itself shows that \(M\) itself is reducible, and hence strongly normalizing.

That recursive definition over arrow types packs genuine logical strength, and the standard account pinpoints why.

The deep reason why reducibility works where combinatorial intuition fails is its logical complexity. Indeed, we have: t ∈ REDU→V iff ∀u (u ∈ REDU ⇒ tu ∈ REDV) We see that in passing to U→V, REDU has been negated, and a universal quantifier has been added. In particular the normalisation argument cannot be directly formalised in arithmetic because t ∈ REDT is not expressed as an arithmetic formula in t and T.

—Jean-Yves Girard, Yves Lafont and Paul Taylor, Proofs and Types (1989). Cambridge Tracts in Theoretical Computer Science 7, Cambridge University Press (web reprint of 2003), Section 6.1, p. 42. REDT is the set of reducible terms of type T; the formula after "we have" is a display in the book.

Each arrow \(A \to B\) adds another universal quantifier to the statement that a term of that type is reducible, so no single formula of first-order arithmetic expresses reducibility uniformly across all types. For the pure simply typed calculus, any individual term involves only finitely many types of bounded depth, allowing strong normalization to be formalized inside Peano arithmetic. For the stronger calculi of Section 2.5 no such workaround exists: there strong normalization implies the consistency of arithmetic itself, which by Gödel's second incompleteness theorem arithmetic cannot prove (Section 3.5).The same book, opening of chapter 6, p. 41: for the simply typed calculus "there is proof theoretic techniques which make it possible to express the argument of the proof in arithmetic, and even in a very weak system"; for Gödel's T, "strong normalisation implies the consistency of PA, which means that it cannot itself be proved in PA". PA is Peano arithmetic (Section 2.5).

What a simple type does not bound is how far away the normal form sits. Guaranteed termination is very different from fast execution, as a term of four numerals demonstrates.

Example 2.4.2 (four twos). Write the Church numeral \(\bar 2 = \lambda f.\,\lambda x.\, f\,(f\,x)\) of Section 1.3 four times in a row to form \(\bar 2\,\bar 2\,\bar 2\,\bar 2 = ((\bar 2\,\bar 2)\,\bar 2)\,\bar 2\), a compact term of 31 nodes, and reduce it to normal form in the page under both innermost-first and leftmost-outermost reduction while recording β-steps, node counts, and wall-clock times. Although \(\bar 2\,\bar 2\) resembles self-application, the whole expression is simply typed because each copy of \(\bar 2\) stands at a higher type than its right-hand neighbor: \(\bar 2\) admits the schema \(\mathsf{N}_A = (A \to A) \to A \to A\) for any type \(A\), so the rightmost numeral takes \(A = o\), each numeral to the left instantiates \(A\) at \(B \to B\) for the \(B\) of its right neighbor, and the leftmost numeral reaches a type of order 5 (a base type has order 0, and \(A \to B\) has order equal to the larger of the order of \(B\) and one plus the order of \(A\)). Because applying one positive Church numeral to another computes exponentiation (\(\bar m\,\bar n \twoheadrightarrow_\beta \overline{n^m}\) for \(m \ge 1\)), the normal form is the Church numeral for \(2^{2^{2^2}} = 65{,}536\), a term of 131,075 nodes. Innermost reduction reaches it in 63 β-steps versus 192,756 β-steps for leftmost-outermost reduction; yet because those 63 innermost steps copy intermediate subterms tens of thousands of nodes wide, both runs took nearly the same wall-clock time: 62 and 76 ms, medians of five runs each under Node on the 16-core server of this series (58 and 83 ms in a second measurement), confirming again that β-step counts do not measure work. Appending a fifth \(\bar 2\) yields a well-typed term of 39 nodes whose normal form represents \(2^{65{,}536}\), with a node count 19,729 digits long: Theorem 2.4.1 guarantees that every reduction of it ends, and none will ever finish in the physical world. ◁

Towered numerals are no isolated quirk: they hit the exact worst-case bound of the simply typed calculus, and no clever algorithm for testing \(=_\beta\) without full reduction can escape towers of exponentials.

Theorem 2.4.3 (how long). In the simply typed lambda calculus: (i) Say that a term has order \(k\) if \(k\) is the largest order among the types of its subterms, and size \(n\) if it has \(n\) nodes. For each \(k \ge 1\), the greatest length of a reduction sequence that starts from a term of order \(k\) and size \(n\) is \(\exp_k(\Theta(n))\), where \(\exp_0(x) = x\) and \(\exp_{k+1}(x) = 2^{\exp_k(x)}\). (ii) Whether two closed terms are convertible, that is, reduce to one normal form, is decidable and not elementary recursive: no algorithm decides it in a time bounded by a tower of exponentials of fixed height in the size of the two terms.(i) is A. Beckmann's theorem, as stated in K. Asada, N. Kobayashi, R. Sin'ya and T. Tsukada, "Almost every simply typed λ-term has a long β-reduction sequence", Logical Methods in Computer Science 15(1), 2019 (arXiv:1801.03886), p. 16:1, there for every \(k \ge 0\) (a term of order 0 is a single variable) and with the order and the size of their Definition 2.2. (ii): R. Statman, "The typed λ-calculus is not elementary recursive", Theoretical Computer Science 9 (1979), pp. 73–81.

"Decidable", for the equality of typed terms, is a mathematical guarantee rather than a promise of speed: a proof kernel that decides equality by computing relies on being handed terms whose reductions stay short, part of the practical craft of Sections 6.3 and 10.4. Section 2.7 feeds the tower of twos to Lean.

Still uncounted is what expressive power was lost when types banished fixed points.

What types can compute

What does guaranteed halting cost in expressive power? Lean faces that same question on every recursive definition, requiring an explicit proof that recursion ends (Section 8.3). Without fixed points or built-in recursion, every function definable in the pure simply typed calculus is total, and on uniformly typed Church numerals almost nothing survives.

Theorem 2.5.1 (numerals of one type). Let \(\mathsf{N}_o = (o \to o) \to o \to o\), the type of the Church numerals over a base type \(o\). The functions \(\mathbb{N}^k \to \mathbb{N}\) defined by the closed terms of type \(\mathsf{N}_o \to \cdots \to \mathsf{N}_o \to \mathsf{N}_o\) of the simply typed lambda calculus are exactly the extended polynomials: the functions built from the variables, 0 and 1 by addition, multiplication and the two tests \(\mathrm{sg}\) (0 at 0, and 1 elsewhere) and \(\overline{\mathrm{sg}}\) (1 at 0, and 0 elsewhere).Statman (1979), Proposition 2, p. 75, credited there to H. Schwichtenberg ("Definierbare Funktionen im λ-Kalkül mit Typen", Archiv für mathematische Logik 17, 1975–76) and to Statman.

From \(1\) upward, any one-variable extended polynomial reduces to an ordinary polynomial with natural-number coefficients, so neither \(n \mapsto 2^n\) nor even the predecessor \(n \mapsto n - 1\) admits a closed term of uniform type \(\mathsf{N}_o \to \mathsf{N}_o\). Both can still be written as simply typed terms by typing the input numeral \(n\) at a larger type than the output numeral: \(\lambda n.\, n\,\bar 2\) takes \(n\) at \(\mathsf{N}_{o \to o}\) and returns a numeral at \(\mathsf{N}_o\), which is how Example 2.4.2 typed its tower of twos. Because outputs at \(\mathsf{N}_o\) cannot be composed back into inputs expecting \(\mathsf{N}_{o \to o}\), genuine numerical functions have to take and return their numerals at one common type.

Two classic extensions restore vast computational strength while preserving strong normalization. The first makes natural numbers and structural recursion over them primitive.

terms   add   = λm n. rec m (λk r. succ r) n            1 recursor, returning a Nat
        mul   = λm n. rec 0 (λk r. add m r) n           2 recursors, nested, each returning a Nat
        exp   = λm n. rec 1 (λk r. mul m r) n           3 recursors, nested, each returning a Nat
        tower = λn. rec 1 (λk r. exp 2 r) n             4 recursors, nested, each returning a Nat
        ack   = λm. rec (λn. succ n) (λk f n. rec (f 1) (λj r. f r) n) m
                its recursor returns a Nat → Nat, and inside it one returns a Nat

rows    n =        0     1     2     3     4     5     6      beside it, by recursion on numbers alone
        ack 0      1     2     3     4     5     6     7
        ack 1      2     3     4     5     6     7     8      add 2 n   2 3 4 5 6 7 8
        ack 2      3     5     7     9    11    13    15      mul 2 n   0 2 4 6 8 10 12
        ack 3      5    13    29    61   125   253   509      exp 2 n   1 2 4 8 16 32 64
        ack 4     13    stopped after 2,000,000 steps         tower n   1 2 4 16, then stopped

ack (k + 1) = step k (ack k) = λn. rec (ack k 1) (λj r. ack k r) n: every unfolding of the outer recursor
returns a function. ack 3 6 = 509 takes 344,476 steps (beta and rec).
Lean 4.35.0, the same term on Nat.rec with the motive fun _ => Nat → Nat: #reduce ack 3 6 prints 509.
(the live figure needs JavaScript; it loads no data)
Five terms of Gödel's T and the rows they compute. Green: the recursor of ack, whose values are functions, and the row its latest unfolding returned; in ink, the rows before. Dashed: add 2, mul 2, exp 2 and tower, which recurse on numbers alone. Every point is a run of the term in the page, its steps counted; a run stopped at 2,000,000 steps leaves the canvas dashed, tower as soon as ack 4. The runs do not show recursion on numbers falling short: that no such term gives every row is a theorem. Step to unfold once more. The readout adds Lean 4.35.0's answer.

What gives Gödel's T its reach is a single freedom: its recursor \(\mathsf{rec}\,z\,s\,n : A\) may return a value of any simple type \(A\), including higher-order function types. Let \(\mathsf{rec}\) return a function \(\mathsf{Nat} \to \mathsf{Nat}\), and one short term computes every row of Ackermann's table, building each row by iterating the entire function from the row before.

Definition 2.5.2 (Gödel's T). Add to the simply typed lambda calculus a base type \(\mathsf{Nat}\) with the terms \(0 : \mathsf{Nat}\) and \(\mathsf{succ}\,M : \mathsf{Nat}\) for \(M : \mathsf{Nat}\), and for every type \(A\) a recursor: \(\mathsf{rec}\,z\,s\,n : A\) whenever \(z : A\), \(s : \mathsf{Nat} \to A \to A\) and \(n : \mathsf{Nat}\). Add to the beta rule the two reductions

\[\mathsf{rec}\,z\,s\,0 \;\to\; z, \qquad \mathsf{rec}\,z\,s\,(\mathsf{succ}\,n) \;\to\; s\,n\,(\mathsf{rec}\,z\,s\,n).\]

At each successor step, \(s\) receives both the predecessor \(n\) and the recursive result \(\mathsf{rec}\,z\,s\,n\) computed so far.Girard, Lafont and Taylor, Sections 7.1 and 7.2, whose T also has a type of booleans and whose step takes its two arguments in the other order; the order here is Lean's. The system goes back to a lecture of Gödel's in 1941 and was printed in 1958 (J. Avigad and S. Feferman, "Gödel's functional ('Dialectica') interpretation", chapter VI of the Handbook of Proof Theory, 1998, Section 1.2). Specializing \(A\) to \(\mathsf{Nat}\) gives ordinary primitive recursion, \(f(0) = z\) and \(f(n + 1) = s(n, f(n))\); the predecessor, which cost \(2n + 5\) β-steps on Church numerals at every \(n\) tested in Section 1.3, drops to \(\lambda n.\, \mathsf{rec}\,0\,(\lambda k\,r.\, k)\,n\), whose step simply returns \(k\). Specializing \(A\) to \(\mathsf{Nat} \to \mathsf{Nat}\) makes the intermediate result an entire function, unlocking fast-growing hierarchies while keeping every term strongly normalizing.

Theorem 2.5.3 (what T computes). (i) Every term of T is strongly normalizing and has exactly one normal form, and a closed normal term of type \(\mathsf{Nat}\) is a numeral \(\mathsf{succ}^n\,0\). (ii) The functions defined by the closed terms of type \(\mathsf{Nat} \to \mathsf{Nat}\) are exactly the computable functions that Peano arithmetic, the first-order theory of the natural numbers with induction, proves to be total. (iii) A closed term of type \(\mathsf{Nat} \to \cdots \to \mathsf{Nat}\) in which every recursor returns a number defines a primitive recursive function.(i) and (ii): Girard, Lafont and Taylor, Sections 7.2 and 7.4; Avigad and Feferman, Corollary 3.2.4 and Theorem 4.4.3. (iii): Avigad and Feferman, Theorem 5.1.1, for the restriction of T to recursors whose values are numbers.

Part (iii) isolates where the jump over primitive recursion comes from: recursors whose return values are functions. Ackermann's function is the benchmark example.

Example 2.5.4 (Ackermann's function in T). The interactive figure above runs five terms of T in the browser under call-by-value reduction (reducing an argument before applying a function to it), counting β-steps and recursor steps together up to a cap of 2,000,000 steps: addition, multiplication, exponentiation, and an exponential tower, whose recursors all return numbers of type \(\mathsf{Nat}\), alongside \(\mathsf{ack}\), whose outer recursor returns a function \(\mathsf{Nat} \to \mathsf{Nat}\). Within that budget, \(\mathsf{ack}\) completes four rows of Ackermann's table. Across the fourth row, \(\mathsf{ack}\,3\,n\) equals \(2^{n+3} - 3\) at every \(n\) tested, rising from 5 at 0 to 509 at 6, with the last value taking 344,476 steps; of the fifth row, only \(\mathsf{ack}\,4\,0 = 13\) finishes before hitting the step cap. Finite runs alone cannot show number-valued recursion falling short: the primitive recursive tower reaches \(2^{16}\) at 4, exceeding every entry in the four completed rows of \(\mathsf{ack}\), and hits the 2,000,000-step cap at 5 just as \(\mathsf{ack}\,4\,1\) does. Separating the two takes Theorem 2.5.3 (iii): terms whose recursors return numbers alone compute only primitive recursive functions, whereas \(\mathsf{ack}\), obtained by a single recursion at type \(\mathsf{Nat} \to \mathsf{Nat}\), "grows more quickly than all the primitive recursive functions".Girard, Lafont and Taylor, Section 7.3.2, p. 50, of a function defined by iterating an iteration, which they call Ackermann's function. ◁

The same book sums up part (ii) of the theorem, with Int for \(\mathsf{Nat}\) and with bars around a closed term for the function it computes.

Summing up, the termination is provable in arithmetic: we say that |t| is provably total in PA.

The converse is true: let f be a recursive function, provably total in PA, then one can find a term of type Int→Int in T, such that f(n) = |t|(n) for all n. In other words, the expressive power of the system T is enormous, and much more than what is feasible on a computer! The further generalisations are not aiming to increase the class of representable functions, which is already too big, but only to enlarge the class of particular algorithms calculating simple given functions. For example, finding a type system where the predecessor is well-behaved.

—Girard, Lafont and Taylor, Proofs and Types (1989). Section 7.4.2, p. 52, two consecutive paragraphs. PA is Peano arithmetic. The book has a footnote at "feasible", left out here: "In the sense of complexity. Thus for instance hyperexponential algorithms, such as the proof of cut elimination, are not feasible."

The price was named in Section 2.4: that every term of T halts cannot be proved in Peano arithmetic. A calculus that computes everything a theory proves total cannot be proved total in that theory: if it were, the theory would prove total the diagonal function of Proposition 2.5.7 below, which no term of the calculus computes.

In Lean the recursor is Nat.rec, which Lean generates from the declaration of the natural numbers (Section 5.6), and Ackermann's function is written on it as in T; #print shows a declaration and #reduce normalizes a term.

#print Nat.rec

def ack (m : Nat) : Nat → Nat :=
  Nat.rec (motive := fun _ => Nat → Nat) (fun n => Nat.succ n)
    (fun _ f n => Nat.rec (motive := fun _ => Nat) (f 1) (fun _ r => f r) n) m

#reduce ack 3 6
recursor Nat.rec.{u} {motive : Nat → Sort u} (zero : motive Nat.zero) (succ : (n : Nat) → motive n → motive n.succ)
  (t : Nat) : motive t
number of parameters: 0
number of motives: 1 (position 1)
number of minor premises: 2 (positions 2–3)
number of indices: 0
major premise position: 4
rules:
  Nat.rec zero succ Nat.zero
    ==> zero
  Nat.rec zero succ n.succ
    ==> succ n (Nat.rec zero succ n)
509

The two computation rules Lean prints match Definition 2.5.2 verbatim, while the header lines describe Nat.rec in the dependent-type vocabulary of Section 5.6: motive specifies the return type, which Lean allows to vary with the number t whereas T keeps constant, and fun _ => Nat → Nat selects recursion whose values are functions.

The second classic extension, System F, adds no primitive Nat or rec constants at all. In Theorem 2.5.1, pure simple types crippled Church numerals because each numeral had to fix a single iteration type \(o\) in advance. System F removes that bottleneck by letting a term take a type as an argument.

Definition 2.5.5 (System F). The types are type variables \(\alpha\), function types \(A \to B\) and universal types \(\forall \alpha.\, A\). The terms are those of the simply typed lambda calculus together with type abstraction \(\Lambda \alpha.\, M\) and type application \(M\,[B]\), typed by

\[\frac{\Gamma \vdash M : A}{\Gamma \vdash \Lambda \alpha.\, M : \forall \alpha.\, A}\;\;(\alpha \text{ not free in } \Gamma) \qquad\qquad \frac{\Gamma \vdash M : \forall \alpha.\, A}{\Gamma \vdash M\,[B] : A[\alpha := B]}\]

and reduced by beta and by \((\Lambda \alpha.\, M)\,[B] \to M[\alpha := B]\).

One polymorphic type now fits every Church numeral: \(\bar 2\) is \(\Lambda\alpha.\,\lambda f{:}\alpha \to \alpha.\,\lambda x{:}\alpha.\, f\,(f\,x)\), of type \(\mathsf{N} = \forall\alpha.\,(\alpha \to \alpha) \to \alpha \to \alpha\). Exponentiation becomes \(\lambda m{:}\mathsf{N}.\,\lambda n{:}\mathsf{N}.\,\Lambda\alpha.\; n\,[\alpha \to \alpha]\,(m\,[\alpha])\), of uniform type \(\mathsf{N} \to \mathsf{N} \to \mathsf{N}\): the ad-hoc trick of Example 2.4.2, choosing a higher type \(\alpha \to \alpha\) for the outer numeral and \(\alpha\) for the inner one, turns into an explicit type argument inside the term. Booleans, pairs, and lists can all be defined in the same polymorphic style with zero added constants.

Now the normalization and expressiveness questions asked of T return for System F, joined by the type-inference question of Section 2.3: if type annotations and type arguments \([B]\) are erased, can an algorithm still infer whether a bare term is typable?

Theorem 2.5.6 (what F computes). (i) Every term of System F is strongly normalizing and has exactly one normal form. (ii) The functions on the natural numbers that F represents are exactly the computable functions that second-order Peano arithmetic, which quantifies over sets of numbers as well as over numbers, proves to be total. (iii) For terms written without their types and type arguments, whether a term can be typed in F is undecidable.Girard, Lafont and Taylor, Section 11.1 (the system, with ΠX.V for \(\forall\alpha.\,A\)), chapter 14 (normalization) and chapter 15 (representation, proved for numerals of the type ΠX. X→(X→X)→X). In 1989 they wrote: "For second order systems, unlike the simpler ones, there is no known alternative proof". (iii): J. B. Wells, "Typability and type checking in the second-order lambda-calculus are equivalent and undecidable", Proceedings of the Ninth Annual IEEE Symposium on Logic in Computer Science, 1994, pp. 176–185.

The quantifier of \(\forall\alpha.\,A\) ranges over all types, the one being formed among them, and self-application, shut out in Section 2.1, returns in typed form: \(\lambda x{:}(\forall\alpha.\,\alpha \to \alpha).\; x\,[\forall\alpha.\,\alpha \to \alpha]\,x\) applies the polymorphic identity to its own type and then to itself, and has the type \((\forall\alpha.\,\alpha \to \alpha) \to (\forall\alpha.\,\alpha \to \alpha)\). This is a totality with a member defined in terms of it, the thing the vicious-circle principle forbade, and the book says so.

The naïve interpretation of the “Π” type is that an object of type ΠX.V is a function which, to every type U, associates an object of type V[U/X].

This interpretation runs up against a problem of size: in order to understand ΠX.V, it is necessary to know all the V[U/X]. But among all the V[U/X] there are some which are (in general) more complex than the type which we seek to model, for example V[ΠX.V/X]. So there is a circularity in the naïve interpretation, and one can expect the worst to happen. In fact it all works out, but the system is extremely sensitive to modifications which are not of a logical nature.

—Girard, Lafont and Taylor, Proofs and Types (1989). Section 11.2, p. 82; ΠX.V is the book's \(\forall \alpha.\, A\) and V[U/X] its \(A[\alpha := B]\). Girard found the system in 1970, as the calculus that gives the first procedure of cut elimination for second-order logic. J. C. Reynolds found "almost the same system" in 1974, looking for a way to write one sorting function for arrays of every type ("Towards a theory of type structure", Colloque sur la programmation, Paris, 1974, Lecture Notes in Computer Science 19, pp. 408–425), and presented it in Paris, where Girard was teaching; by the historians' account "nobody in the audience noticed the similarity of the two systems" (Cardone and Hindley, Section 8.3, p. 37).

How does Girard's normalization proof escape that circularity? In Section 2.4, Tait defined reducibility at \(A \to B\) from reducibility at the syntactically smaller types \(A\) and \(B\). At \(\forall\alpha.\,A\), trying to define reducibility of \(M\) from reducibility of \(M\,[B]\) at the substituted type \(A[\alpha := B]\) breaks structural induction on types, because choosing \(B = \forall\alpha.\,A\) makes \(A[\alpha := \forall\alpha.\,A]\) larger than \(\forall\alpha.\,A\) itself. Girard broke that syntactic loop with reducibility candidates: instead of asking for "the" not-yet-defined reducibility set of \(B\), pair the type variable \(\alpha\) with any set \(\mathcal{C}\) of strongly normalizing terms of type \(B\) that obeys the three closure properties proved in Section 2.4 (each such set \(\mathcal{C}\) is called a reducibility candidate for \(B\)). Because the body \(A\) has strictly fewer type constructors than \(\forall\alpha.\,A\), reducibility inside \(A\) relative to assigning \(\mathcal{C}\) to \(\alpha\) is already well-defined by induction on \(A\), and \(M : \forall\alpha.\,A\) is declared reducible when \(M\,[B]\) is reducible in that sense for every type \(B\) and every candidate \(\mathcal{C}\) for \(B\). Impredicativity has not vanished: it has moved out of type syntax into the set-theoretic metatheory of the proof, which defines a candidate set by quantifying over all candidate sets (itself included), requiring proof-theoretic strength beyond second-order Peano arithmetic, whose consistency the theorem implies.

Vast as Gödel's T and System F are, both still omit some total computable functions, as every strongly normalizing calculus must: in Section 1.5, Cantor's diagonal argument failed in the untyped calculus only because some terms had no normal form.

Proposition 2.5.7 (no total calculus defines its own evaluator). Code the terms of F by numbers. The function that takes the code of a term to the code of its normal form is computable and total, and no term of F represents it. The same holds of every calculus in which every term has exactly one normal form and the functions used in the proof are represented.

Proof. If the evaluator were represented, so would be the function \(D\) for which \(D(n)\) is one more than the value of the term with code \(n\) applied to the numeral \(n\) (taken as 0 when that is not a number), since coding, application and decoding are represented by terms. Let \(n_0\) be the code of a term for \(D\). Applied to the numeral \(n_0\) that term has the value \(D(n_0)\), so \(D(n_0) = D(n_0) + 1\). ∎

Proposition 2.5.7 states the exact price announced at the opening of this part. The diagonal argument, Girard, Lafont, and Taylor remark, "applies to all sorts of calculi, typed or untyped, which satisfy the normalisation theorem":Girard, Lafont and Taylor, Section 15.1.2, p. 121, where the result is called a variant of Turing's theorem that no total computable function enumerates the total computable functions. any language in which every legal program halts is inevitably at least one total computable function short. How Lean handles definitions whose termination its kernel cannot see directly is the subject of Section 8.3.

What each calculus computes, and where its halting is proveda row to a calculus, from no types to System F; in ink, a term of it

  1. 1.5the untyped calculus Section 1

    Anything may be applied to anything. It defines every computable function; a term may run forever, and no algorithm decides whether a given term has a normal form.

    Ω = (λx. x x) (λx. x x)

    no type, no normal form

  2. 2.4simple types Church, 1940

    Every term halts. On numerals of one type it defines the extended polynomials and nothing else: no exponential, no predecessor. That it halts can be proved in arithmetic.

    2 : (o → o) → o → o

  3. 2.5Gödel's T 1941, printed 1958

    Numbers, and recursion with values of any type. Every term halts. It defines exactly the functions that Peano arithmetic proves total, and that it halts cannot be proved in Peano arithmetic.

    rec z s (succ n) → s n (rec z s n)

  4. 2.5System F Girard, 1970; Reynolds, 1974

    Terms take types as arguments, and one type fits all numerals. Every term halts. It defines exactly the functions that second-order arithmetic proves total, and that it halts cannot be proved there.

    2 : ∀α. (α → α) → α → α

Neither T nor System F is Lean's logic yet: in both, types can never mention an ordinary value like a number \(n\).

The cube

System F lets a term depend on a type, alongside the simply typed calculus where a term depends on a term. Two further directions of dependency are just as natural: a type can depend on a type (as List α depends on the element type α), and a type can depend on a term (as Vec n, the type of length-n vectors, or Prime n, the proposition that n is prime, depends on the number n). Allowing or forbidding each of the three extra directions independently produces eight calculi at the corners of Henk Barendregt's lambda cube. Lean's kernel typing rules are written in the cube's unified language (Section 6.2), and so is the paradox of assuming a type of all types (Section 5.5).

cube     the 8 systems; from λ→, up adds the rule (□,*), back adds (□,□), right adds (*,□)

              λω ───────── λC
             ╱ │          ╱ │
           λ2 ───────── λP2 │
            │  λω̲ ───────│─ λPω̲
            │ ╱          │ ╱
           λ→ ───────── λP

terms    the 6 test terms                       the rules it needs beside (*,*)     typed in
         the identity at one type               none                                all 8 systems
         the identity for all types             (□,*) terms depending on types      4: λ2 λω λP2 λC
         a type operator                        (□,□) types depending on types      4: λω̲ λω λPω̲ λC
         a function on vectors of length n      (*,□) types depending on terms      4: λP λP2 λPω̲ λC
         a proof that all x satisfy Q           (*,□) types depending on terms      4: λP λP2 λPω̲ λC
         Leibniz equality                       all three                           1: λC

chosen   λ2, System F, with the rules (*,*) (□,*): it types 2 of the 6 terms and refuses the other 4.
Lean 4.35.0 accepts all six terms, with * read as Prop or as Type (recorded).
(the live figure needs JavaScript; it loads no data)
The eight type systems of the lambda cube, an axis to a rule: up, terms depending on types; back, types depending on types; right, types depending on terms. Green: the system chosen; in ink, the edges of the systems it contains. Under each name, a mark to each of six test terms: a square where the system types it, hatched where it refuses it. The rows give each term's judgment and its type in the system shown, or the checker's reason for refusing it. Tour the systems, click a vertex, point at a row. Checked in the page; the readout adds Lean 4.35.0's answer.

Across the six test expressions in the figure, a term is typable at precisely the corners whose rule set covers every kind of dependency used to form the term. The simply typed calculus \(\lambda{\to}\) types only the first, while the opposite corner \(\lambda C\) types all six; the sixth, Leibniz's definition of equality (\(x\) equals \(y\) when every predicate holding of \(x\) also holds of \(y\)), combines all three extra axes at once and is typable at \(\lambda C\) alone. Expressing all eight systems with a single compact set of rules requires merging terms and types into one shared grammar classified by sorts, with a dependent function type \(\Pi x{:}A.\, B\) (whose output type \(B\) may mention the input variable \(x : A\)) unifying arrows \(A \to B\) and universal types \(\forall\alpha.\, A\).

Definition 2.6.1 (pure type system). Fix a set of sorts, a set of axioms \(s_1 : s_2\) between sorts and a set of rules, which are pairs \((s_1, s_2)\) of sorts. The terms are

\[M, A \;::=\; s \;\mid\; x \;\mid\; \Pi x{:}A.\, B \;\mid\; \lambda x{:}A.\, M \;\mid\; M\,N,\]

with \(s\) a sort and no separate grammar of types: \(A \to B\) abbreviates \(\Pi x{:}A.\, B\) when \(x\) does not occur in \(B\). The judgments \(\Gamma \vdash M : A\) are derived by seven rules, in which \(x\) is a variable not yet in \(\Gamma\):

\[\begin{aligned} &\text{(sort)} && \vdash s_1 : s_2 && \text{if } s_1 : s_2 \text{ is an axiom} \\ &\text{(var)} && \Gamma \vdash A : s \;\Longrightarrow\; \Gamma,\, x : A \vdash x : A \\ &\text{(weak)} && \Gamma \vdash M : B,\;\; \Gamma \vdash A : s \;\Longrightarrow\; \Gamma,\, x : A \vdash M : B \\ &(\Pi) && \Gamma \vdash A : s_1,\;\; \Gamma,\, x : A \vdash B : s_2 \;\Longrightarrow\; \Gamma \vdash \Pi x{:}A.\, B : s_2 && \text{if } (s_1, s_2) \text{ is a rule} \\ &(\lambda) && \Gamma,\, x : A \vdash M : B,\;\; \Gamma \vdash \Pi x{:}A.\, B : s \;\Longrightarrow\; \Gamma \vdash \lambda x{:}A.\, M : \Pi x{:}A.\, B \\ &\text{(app)} && \Gamma \vdash M : \Pi x{:}A.\, B,\;\; \Gamma \vdash N : A \;\Longrightarrow\; \Gamma \vdash M\,N : B[x := N] \\ &\text{(conv)} && \Gamma \vdash M : A,\;\; \Gamma \vdash B : s,\;\; A =_\beta B \;\Longrightarrow\; \Gamma \vdash M : B \end{aligned}\]

Specializing this Pure Type System framework to two sorts \(\ast\) and \(\square\) turns each of the three dependency axes into a single pair \((s_1, s_2)\) governing the \((\Pi)\) rule.

Definition 2.6.2 (the cube). The eight systems of the cube are the pure type systems with the sorts \(\ast\) and \(\square\), the axiom \(\ast : \square\), the rule \((\ast, \ast)\) and any of the three rules \((\square, \ast)\), \((\square, \square)\) and \((\ast, \square)\).H. Barendregt and H. Geuvers, "Proof-assistants using dependent type systems", chapter 18 of the Handbook of Automated Reasoning (2001), Definition 3.24 and Figure 3; in general a rule names a third sort, that of the product, which in these eight systems is always the second. The cube is Barendregt's ("Introduction to generalized type systems", Journal of Functional Programming 1(2), 1991, pp. 125–154); pure type systems, which generalize it, were introduced by Berardi (1988) and Terlouw (1989).

An expression \(A\) with \(A : \ast\) is an ordinary type, and \(\ast : \square\) gives \(\ast\) itself a sort so type variables \(A : \ast\) can be declared in contexts just like value variables. In rule \((\Pi)\), a pair \((s_1, s_2)\) allows forming functions from inputs whose domain lives in \(s_1\) to outputs whose codomain lives in \(s_2\). With \((\ast, \ast)\) alone, terms depend on terms (\(A \to B\)), recovering the simply typed calculus \(\lambda{\to}\) with base types declared as context variables \(A : \ast\). Adding \((\square, \ast)\) lets terms depend on types: \(\Lambda\alpha.\, M\) becomes \(\lambda\alpha{:}\ast.\, M\) and \(\forall\alpha.\, A\) becomes \(\Pi\alpha{:}\ast.\, A\), recovering System F. Adding \((\square, \square)\) lets types depend on types (\(\ast \to \ast\)), as List depends on its element type. Adding \((\ast, \square)\) lets types depend on terms, where the bound variable \(x\) inside \(\Pi x{:}A.\, B\) becomes essential: a function mapping each number \(n\) to a vector of length \(n\) has the dependent type \(\Pi n{:}\mathsf{Nat}.\, \mathsf{Vec}\,n\), which cannot be written as a non-dependent arrow.

Because each extra pair \((s_1, s_2)\) widens what may be applied to what, strong normalization has to be verified anew across all eight corners, and contrasted against the tempting collapse \(\ast : \ast\) in which the sort of all types is itself a type.

Theorem 2.6.3 (normalization in the cube). Every typable term of each of the eight systems is strongly normalizing. The system with the one sort \(\ast\), the axiom \(\ast : \ast\) and the rule \((\ast, \ast)\), in which the type of all types is a type, is not strongly normalizing.Barendregt and Geuvers (2001), Theorem 3.33 and Corollary 3.34, pp. 1200–1201. The calculus of constructions is T. Coquand and G. Huet's ("The calculus of constructions", Information and Computation 76, 1988, pp. 95–120).

The corner combining all four rules is Coquand and Huet's Calculus of Constructions (\(\lambda C\)). Lean's core logic grows directly out of that corner, replacing the two-sort step \(\ast : \square\) with an infinite ladder of universes and adding primitive inductive types (Sections 5 and 6). Among the three extensions, \((\ast, \square)\) is what makes type theory a language for mathematics: "\(n\) is prime" and "a vector of length \(n\)" are types indexed by a term (Section 5.1). Meanwhile, collapsing the hierarchy via \(\ast : \ast\) revives the paradoxes of Section 2.1: Girard's paradox refutes \(\ast : \ast\) (not System F) and is constructed in Section 5.5.

In Lean

How does Lean 4.35.0 handle these typed terms? The #check command computes the typing judgment of Section 2.2, printing an expression together with its inferred type in a file that imports nothing at all.

variable (A B : Type)

#check fun (x : A → A) (y : A) => x (x y)

def selfApply (x : A) := x x

def wrongArgument (f : A → B) (x : B) := f x
fun x y => x (x y) : (A → A) → A → A
Types.lean:5:25: error: Function expected at
  x
but this term has type
  A

Note: Expected a function because this term is being applied to the argument
  x
Types.lean:7:43: error: Application type mismatch: The argument
  x
has type
  B
but is expected to have type
  A
in the application
  f x

The first output matches the conclusion of the derivation tree for the numeral 2 in Section 2.1. The two errors match the two failure branches in the app case of Section 2.2's checker: applying an expression whose type is not a function arrow, and passing an argument whose type disagrees with the arrow's domain.

Where Lean uses unification constantly is to solve for implicit arguments. Writing a binder in curly braces, {α : Type}, declares an argument that callers omit; at each call site Lean inserts a fresh metavariable unknown (?m.1, ?m.2, …) and solves for it by unifying surrounding types, as in the standard library's identity function id.

/--
The identity function. `id` takes an implicit argument `α : Sort u`
(a type in any universe), and an argument `a : α`, and returns `a`.
-- ...
-/
@[inline, implicit_reducible] def id {α : Sort u} (a : α) : α := a

Sort u stands for any of Lean's universes, its types of types (Section 5.5), of which Type, the universe of ordinary data, is one; u is declared as a universe variable at the head of the file. An @ before a name makes its hidden arguments explicit, and the option pp.explicit has Lean print them.

#check @id
#check id true

set_option pp.explicit true in
#check id true

set_option pp.explicit true in
#check id id
@id : {α : Sort u_1} → α → α
id true : Bool
@id Bool true : Bool
@id (?m.2 → ?m.2) (@id ?m.2) : ?m.2 → ?m.2

In id true, seeing true : Bool lets unification solve α := Bool. In id id, the two copies of id are instantiated at different types, the outer at ?m.2 → ?m.2 and the inner at ?m.2, just as the twos of Example 2.4.2 stood at successively higher types; no single variable is applied to itself at one type, and ?m.2 stays unconstrained because any type works.

Because types are first-class expressions in Lean, System F's type abstraction \(\Lambda\alpha\) is written with an ordinary fun, allowing the exponential tower of Example 2.4.2 to be typed in a standalone file with each two instantiated at its required type.

def N (α : Type) : Type := (α → α) → α → α
def two (α : Type) : N α := fun f x => f (f x)

#reduce two (Nat → Nat) (two Nat) Nat.succ 0
#reduce two (N Nat) (two (Nat → Nat)) (two Nat) Nat.succ 0
#reduce two (N (Nat → Nat)) (two (N Nat)) (two (Nat → Nat)) (two Nat) Nat.succ 0
#eval two (N (Nat → Nat)) (two (N Nat)) (two (Nat → Nat)) (two Nat) Nat.succ 0
4
16
Tower.lean:6:0: error: maximum recursion depth has been reached
use `set_option maxRecDepth <num>` to increase limit
use `set_option diagnostics true` to get diagnostic information
65536

At four twos, #reduce stops at Lean's safety limit on symbolic recursion depth rather than any mathematical non-termination, whereas #eval compiles and executes the expression as bytecode to print 65536; Section 8.2 explains why Lean keeps both evaluators.

One final check puts the two choices of Remark 2.1.1 side by side. Over Type, quantifying across all data types in (α : Type) → α → α pushes the resulting function type one universe up into Type 1, causing Lean to reject the System F self-instantiation x ((α : Type) → α → α) x. Over Prop, the universe of propositions, ∀ α : Prop, α → α stays inside Prop itself, and Lean accepts the impredicative self-instantiation silently.

#check (α : Type) → α → α
#check ∀ α : Prop, α → α

example (x : (α : Type) → α → α) := x ((α : Type) → α → α) x
example (x : ∀ α : Prop, α → α) := x (∀ α : Prop, α → α) x
(α : Type) → α → α : Type 1
∀ (α : Prop), α → α : Prop
Circle.lean:4:38: error: Application type mismatch: The argument
  (α : Type) → α → α
has type
  Type 1
of sort `Type 2` but is expected to have type
  Type
of sort `Type 1` in the application
  x ((α : Type) → α → α)

Russell's stratification rule, that whatever quantifies over all of a collection must not belong to that collection, is enforced by Lean on its data universes (Type, Type 1, …) and waived on Prop. Anyone relying on a theorem checked in Lean relies on both halves of that design; Section 5.5 examines the universe hierarchy and Section 5.7 examines impredicative Prop.

A type is a promise about a program that a machine checks without running the program, and in the calculi of this part a program that keeps it halts. The price is exact: a language in which every program halts cannot define its own evaluator, and the proof that its programs halt has to come from a theory stronger than the one whose functions it computes.

The types of this part were labels on programs. Section 3 asks what a proof is, as an object, in what looks like another subject: the trees that logicians call proofs, and the removal of their detours.

← Back to all posts