This part covers Lean both as a practical proof assistant and as the
dependent type theory it is built on. We begin with the natural
numbers — which comes with its constructors as well as with reduction rules.
Then come the types, built together with their terms: universes,
function types, inductive types and structures; the functions on
inductive types, defined by pattern matching and recursion; dependent
pairs, subtypes, type families, propositions as types, and quotients.
A last chapter on types gives the rules behind them, with Prop.
After that come the typeclass system and notation.
(Several reference topics — the alphabetical tactic glossary, how a
Lean file is organized, Lean's brackets, equality and reduction, the
diagnostic commands, and Navigating Mathlib — are covered in the
Appendix; the deeper foundations, the axioms of Lean
and well-foundedness, are treated in the Mathematics part.)
Nat is an inductive type: it is generated by a fixed list of constructors (the different possibilities to construct a natural number), the basic ways to build a value. Nat has exactly two (read a : b as a is a term of type b, and a → b as the type of maps from a to b, and succ means the successor of a natural number):
Nat.zero : Nat
Nat.succ : Nat → Nat
so every natural number is either Nat.zero is 0, or the successor of another natural number, so Nat.succ Nat.zero is 1, Nat.succ (Nat.succ Nat.zero) is 2, and so on. (The numerals 0, 1, 2 are just notation for these terms.) The general inductive declaration comes later; here we need only Nat.
These two constructors are Giuseppe Peano's axiomatization of 1889: a zero, a successor, and induction. Induction is not a third constructor. It is the recursor, generated together with the type, and it is the subject of the next paragraph.
Generated alongside the type is the recursorNat.rec. The constructors build a value; the recursor consumes one. With other words, it is the primitive way to define a function with domain Nat. To define some f : Nat → C (where C is some type), you supply two things: a base value base : C for the zero case (i.e. f 0 := base, where f 0 is the Lean way to write f(0)), and a step : Nat → C → C such that, for succ n (which equals n + 1), you may reuse both n and the result already computed for n, i.e. you define in this way f (n + 1) := step n (f n). (Note the important notation here: We write α → β → γ — with implicit brackets g : α → (β → γ) for a function g mapping every a : α to a function β → γ. So, g a b : γ. Application brackets the other way: g a b means (g a) b, first g a : β → γ, then that function applied to b. Arrows omit brackets on the right, application omits them on the left, and the two fit together. You only write brackets where an argument is itself an application, as in step n (f n); see Different parentheses. In other words, this is the Lean and more flexible way to write a function depending on two variables.)
Noting the example keyword, as well as the inputs C, base, step, we define the terms of type Nat → C by introducing a function (using the fun keyword, and the mapping rule):
Pattern matching and the cases and induction tactics all compile down to Nat.rec. (A more general form lets the result type vary with the Nat, which unifies recursion with the induction principle. It needs universes, so it comes with the inductive types.)
Nat.reccomputes. Applied to a value that is literally one of the two constructors, it selects the matching case by the iota rule (ι), made precise below (numerals such as 2 are put into constructor form first, so the rule applies to them too):
Nat.rec base step Nat.zero ⟶ base
Nat.rec base step (Nat.succ n) ⟶ step n (Nat.rec base step n)
As an example, define "double" through the recursor and reduce it on 2. The keyword def opens the definition, myDouble is the name, n : Nat the input, and _ an unused variable:
myDouble 2 = 4 needs no proof beyond rfl, Lean's way of saying that two terms are definitionally equal: both sides reduce to a common form. The rest of this chapter names those reduction steps and says when two terms are the same by computation.
Lean consists of two parts. The elaborator reads what you write, such as the notation 2 + 2, omitted arguments and tactic proofs, and translates it into a fully explicit term. The kernel checks that term against a small, fixed set of rules, and only a term that passes is accepted. The elaborator is large and may contain bugs; the kernel is small, and it is the only part that has to be trusted. Chapter 1.5 describes both in detail.
Terms in Lean reduce, by a fixed set of steps, toward a simpler form — (fun x => x + 1) 4 becomes 5, and 2 + 2 becomes 4. Each such step is called a reduction and is written term ⟶ simpler term. Two terms are definitionally equal — also judgmentally equal, written a ≡ b — when they reduce to a common form, and Lean's kernel then treats them as fully interchangeable, in particular when it compares types during type-checking. That comparison test is called conversion (or defeq checking). Definitional equality must be kept apart from propositional equalitya = b, which is itself a Prop and may require a genuine proof; the full three-way distinction — syntactic, definitional, propositional — is laid out in the appendix on equality.
The tactic rfl proves exactly a definitional equality. That is why goals whose two sides are written differently but reduce to the same thing close by rfl:
example:2+2=4:=rflexample:Nat.succ0=1:=rfl
The #eval command (introduced with the other commands for terms in the next chapter) computes the value as well and prints it, though by running compiled code rather than by reduction; for the terms of this chapter both give the same result. The steps are the kernel's reduction rules; they recur whenever a later step is claimed to hold "by definition".
Definitional equality is generated by a fixed list of reduction rules that the kernel applies to compute terms. Most of the names come from the lambda calculus of Alonzo Church in the 1930s, where functions are written fun x => e and each rewriting rule carries a Greek letter. Lean's kernel uses six of them:
Rule
Technical name
What it does
Example
α (alpha)
α-conversion
rename a bound variable
fun x => x and fun y => y agree
β (beta)
β-reduction
apply a function: substitute the argument
(fun x => x + 1) 4 ⟶ 4 + 1
η (eta)
η-conversion
a function equals its expansion fun x => f x
fun x => f x ⟶ f
δ (delta)
δ-reduction
unfold a definition: replace a constant by its value
twice 3 ⟶ 2 * 3
ι (iota)
ι-reduction
run a recursor on a constructor
Nat.rec base step (n+1) ⟶ step n (Nat.rec base step n)
ζ (zeta)
ζ-reduction
substitute a let-binding
let x := 4; x + x ⟶ 4 + 4
Here are some examples:
-- beta, then arithmetic computes (delta + iota)example:(funx=>x+1)4=5:=rflexample:2+2=4:=rflexample:List.length[7,8,9]=3:=rfl-- eta: a function equals its eta-expansionexample(f:Nat→Nat):(funx=>fx)=f:=rfl-- zeta: a `let` unfoldsexample:(letx:=4;x+x)=8:=rfl-- iota: a recursor applied to a constructorexample(b:Nat)(s:Nat→Nat→Nat):Nat.rec(motive:=fun_=>Nat)bs0=b:=rflexample(b:Nat)(s:Nat→Nat→Nat)(n:Nat):Nat.rec(motive:=fun_=>Nat)bs(n+1)=sn(Nat.recbsn):=rfl-- delta + iota: a defined function on a literaldeftwice(n:Nat):Nat:=2*nexample:twice3=6:=rfl
Conversely, rflfails when no chain of reductions connects the two sides — typically when a variable blocks computation. Nat's addition is defined by recursion on its second argument, so n + 0 fires the ι rule and reduces to n, whereas 0 + n is stuck: with n a bare variable there is no constructor for the recursor to fire on.
-- `n + 0` reduces to `n`, so this is `rfl`:example(n:Nat):n+0=n:=rfl
Here, the red squiggly line indicates an error, i.e. a proof which does not work.
-- `0 + n` is stuck (nothing to recurse on), so `rfl`-- fails and you need induction (see below) instead:example(n:Nat):0+n=n:=Type mismatchrflhas type?m.9=?m.9but is expected to have type0+n=nrfl
To actually prove 0 + n = n you must run the recursor yourself, and for that you need induction — the full Nat.rec, which hands you the induction hypothesis for the predecessor:
example(n:Nat):0+n=n:=n:ℕ⊢ 0+n=ninductionnwith⊢ 0+0=0All goals completed! 🐙k:ℕih:0+k=k⊢ 0+(k+1)=k+1-- goal: 0 + (k + 1) = k + 1-- ι reduces the LHS to succ (0 + k);-- `Nat.add_succ` makes that step explicit,-- then `ih : 0 + k = k` closes it.All goals completed! 🐙
(Here, rw [...] rewrites the goal using an equation; see the rw tactic.) Note that rw [ih]alone fails here: the goal reads 0 + (k + 1) = k + 1, and the subterm 0 + k is not yet visible — it only appears after the ι step 0 + succ k ⟶ succ (0 + k), which Nat.add_succ performs. This is the same stuck-until-a-constructor-shows-up phenomenon one level down.
Recognizing when a goal is "true by reduction" — and therefore closed by rfl — is one of the most useful instincts to develop.
Reducibility, weak head normal form, and decidability
How eagerly the δ rule fires is governed by reducibility annotations: a @[reducible] definition is unfolded freely, an ordinary def is unfolded on demand, and an @[irreducible] one is left folded. And the kernel usually does not reduce all the way to a normal form; it stops at weak head normal form (WHNF) — just far enough to expose the outermost constructor or binder — which is all that comparing two terms requires. On the terms that occur in practice this terminates, so rfl and the type checker give an answer. In full generality definitional equality in Lean is undecidable, and the checker is sound but incomplete: there are equal terms on which it fails (Conversion in chapter 1.5). The counterexamples are constructed and need Acc.rec, the recursor of well-founded recursion, on proofs.
Bool is simpler than Nat: two values, true and false, and two constructors, neither taking an argument. Its definition, from Lean's core library (where introduces the constructors):
Logically speaking, this is equivalent to Prop (the type of propositions). The distinction is
public important for programming: both propositions and their proofs are erased in the code generator,
while Bool corresponds to the Boolean type in most programming languages and carries precisely one
bit of run-time information.
The Boolean value true, not to be confused with the proposition True.
Its recursor Bool.rec consumes a Bool by offering one value for each constructor — first the false case, then the true case — and returns the matching one. Into a fixed result C : Type, its (non-dependent) signature is just this, exactly as Nat.rec above:
-- the `false` case first, then the `true` case:
Bool.rec : C → C → Bool → C
This is exactly an if-then-else: reading Bool.rec e f b as "if b then f else e" (note the order: the false result e comes first). Applied to a literal constructor it reduces by the ι rule (the reduction rules below). Equivalently (and definitionally equal) is the following construction (read bif as Boolean if):
-- `bif true …` picks the then-branch:example:(biftruethen"Hi"else"Salut")="Hi":=rfl-- and in general `bif b then f else e` is `Bool.rec e f b`:example{α:Type}(ef:α):(biffalsethenfelsee)=Bool.receffalse:=rfl
Note, as above in the 0 + n = n example, the bif fails to reduce if the value of b is unknown:
example(b:Bool):(bifbthen"Hi"else"Salut")=Bool.rec"Salut""Hi"b:=byb:Bool⊢ (bifbthen"Hi"else"Salut")=Bool.rec"Salut""Hi"bTactic `rfl` failed: The left-hand sidebifbthen"Hi"else"Salut"is not definitionally equal to the right-hand sideBool.rec"Salut""Hi"bb:Bool⊢ (bifbthen"Hi"else"Salut")=Bool.rec"Salut""Hi"brflb:Bool⊢ (bifbthen"Hi"else"Salut")=Bool.rec"Salut""Hi"b
The fix is to make a case analysis as follows (cases is a simpler form of induction; see cases and induction):
Instead of calling Bool.rec by hand, you can define a function on Bool by pattern matching: one line per constructor, introduced by |, giving the result for that constructor.
Lean translates such a definition into the recursor, so on constructors it reduces just as Bool.rec does. Pattern matching works for every inductive type, including recursive ones like Nat; it is treated in detail in chapter 1.3.
How bif is defined under the hood
Internally, Lean does not build runnable definitions from Bool.rec directly — the code generator cannot compile a bare recursor, whereas it can compile a match. So bif is not primitive: it is notation for a function cond, which does the actual branching with a match (the inline form of pattern matching, see chapter 1.3):
-- the underlying function, defined by matching on `c`:
def cond {α : Type} (c : Bool) (x y : α) : α :=
match c with
| true => x
| false => y
-- `bif` is *notation* that expands to a `cond` call:
macro "bif " c:term " then " t:term " else " e:term :
term => `(cond $c $t $e)
Both types in this section live in Prop, the universe of propositions. Unlike Bool, Nat, or the True and False below — each an inductive type whose definition you can read off — Prop has no such definition. It is not an inductive type, and there is no def Prop := … to unfold; asking Lean to print it (#print Prop) even fails, because there is nothing written in Lean to print. Instead, Prop is a primitive, baked directly into Lean's kernel: it is the bottom universe Sort 0 (with Type u being Sort (u+1); more on the universe hierarchy in the next chapter). What makes Prop usable is therefore not a definition but the rules the kernel attaches to it — proof irrelevance and the rest, taken up in why Prop is special.
The trivial proposition True.True is the proposition that always holds. Being a Prop, its terms are proofs. It has a single constructor, taking no argument, which is therefore already a complete proof of it (note that the type after the colon is now Prop, not Type):
The term trivial is nothing but a name for this constructor (theorem trivial : True := True.intro), and on a goal True the trivial tactic does exactly this. The tactic also tries a few other simple steps, such as rfl and assumption, before it gives up.
Its recursor has exactly one case, for the single constructor True.intro, so into a fixed result type C its (non-dependent) signature is:
-- one constructor, hence one case:
True.rec : C → True → C
There is correspondingly nothing to learn from a proof of True: the recursor just hands back the value you supplied for that one case (True.rec c h reduces to c), which is why True carries no information.
The empty proposition False.False is the opposite extreme: the proposition that is never true. It is the inductive type with no constructors at all — so its definition has no where clause and no | lines:
False is the empty proposition. Thus, it has no introduction rules.
It represents a contradiction. False elimination rule, False.rec,
expresses the fact that anything follows from a contradiction.
This rule is sometimes called ex falso (short for ex falso sequitur quodlibet),
or the principle of explosion.
For more information: Propositional Logic
Constructors
With no constructor there is no way to build a term of False, as it must be for a statement that has no proof. Its recursor, in full (the result universe Sort u is treated in the next chapter):
Implicit vs. explicit motive: why False.rec looks different
This looks different from Bool.rec and True.rec above for one reason — implicit versus explicit: there the motive sat in curly braces {motive …} and Lean inferred it from the case values, which is why we could drop it and even present those signatures non-dependently as C → C → Bool → C and C → True → C. False has no case values, so nothing lets Lean infer the motive; it is therefore explicit (round brackets (motive …)), and you must supply it — you write False.rec (fun _ => C) h, or False.rec _ h letting the goal fix it, but never plain False.rec h (which would read h as the motive). Note also that between the motive and the input t there is no case argument at all — Bool.rec had two there, True.rec one, False.rec none — which is exactly why its result motive t may be of any type: the principle ex falso quodlibet ("from a falsehood, anything follows"). The filled-in form is packaged as False.elim, so that False.elim h = False.rec (fun _ => C) h.
For ex falso quodlibet, Lean does not use False.rec but False.elim, which is the following:
def False.elim {C : Sort u} (h : False) : C :=
False.rec (fun _ => C) h
This is exactly why False is so important for consistency. Because False.elim turns a single proof of False into a proof of every proposition P (the second example above), one term of type False would make every statement a theorem — and the logic would no longer distinguish the provable from the false.
Lean has the data types every programming language has — int, string, float — and you can define your own, as you will in this course. Throughout, x : α means that x is a term of type α, and def name : α := x gives the term x a name (Commands for terms below):
Here square is a function from ℕ to ℕ, and ℕ → ℕ is itself a type; zeroNeOne is the proposition that 0 and 1 differ. Propositions and types can depend on terms:
-- the proposition n < n + 1 depends on ndefltSucc:Prop:=∀n:ℕ,n<n+1-- the type of vectors in ℝⁿ depends on ndefRVec(n:ℕ):Type:=Finn→ℝdefzeroVec(n:ℕ):RVecn:=fun_=>0
Fin n is the type of the natural numbers less than n; its definition is in Structures below. zeroVec is a function whose value at n lies in the type RVec n, which depends on n.
Two words for terms recur throughout, depending on their type: a term h : P whose type P is a Prop is called a proof (of P), while a term a : α whose type α is a Type u (where u is a universe level, see The universe hierarchy below) is called data. So 42 : ℕ and true : Bool are data, whereas any term of the proposition 0 ≠ 1 is a proof of it.
These data types are abstract: Lean treats ℕ as genuinely infinite, not as a machine integer of fixed width. ℕ is the zero/succ construction of the previous chapter.
In Lean every object is a term, and every term has a type. A type is itself a term, so it has a type as well.
This chapter describes every way of forming and using a type in the same four steps.
step
question
Formation
How is the type written?
Construction
How is a term of the type built?
Use
How is a term of the type used?
Computation
What happens when a term that was just built is used?
This chapter treats functions, inductive types and structures. Chapter 1.4 adds pairs and Σ-types (x : α) × β x, subtypes {x : α // P x}, indexed families and quotients Quot r; The four steps at a glance at its end has all type formers in one table.
def name : T := t gives the name name to the term t, after checking that t has type T.
theorem name : P := p does the same for a proposition P and a proof p of it. Mathlib also accepts lemma, with the same meaning; Lean itself knows only theorem.
example : T := t checks that t has type T, without giving it a name.
Three of them show something about a term:
#check t prints the type of the term t.
#eval t computes the value of t and prints it. It runs compiled code; rfl instead asks the kernel to reduce (Definitional equality), and for the definitions of this chapter both give the same value.
#print name prints the definition of name.
deffour:ℕ:=2+2theoremfour_eq:four=4:=rflexample:four=4:=rflfour:ℕ#checkfour-- four : ℕ4#evalfour-- 4deffour : ℕ :=2+2#printfour-- def four : ℕ := 2 + 2
The text after -- is a comment; in the examples it shows what Lean prints.
For a theorem, #print shows the proof as a term, also when tactics found it. The arguments before the colon become ∀ and → in the statement and fun in the proof:
theoremswap_of_and(PQ:Prop)(h:P∧Q):Q∧P:=byP:PropQ:Proph:P∧Q⊢ Q∧PconstructorleftP:PropQ:Proph:P∧Q⊢ QrightP:PropQ:Proph:P∧Q⊢ P·leftP:PropQ:Proph:P∧Q⊢ Qexacth.2All goals completed! 🐙·rightP:PropQ:Proph:P∧Q⊢ Pexacth.1All goals completed! 🐙theoremswap_of_and : ∀(PQ:Prop),P∧Q→Q∧P :=funPQh=>⟨h.right,h.left⟩#printswap_of_and-- theorem swap_of_and : ∀ (P Q : Prop), P ∧ Q → Q ∧ P :=-- fun P Q h => ⟨h.right, h.left⟩
Every type is itself a term, so it has a type as well. These types of types are called universes. They form a countably infinite tower, which is what keeps the system consistent.
At the bottom sit the two universes you meet first:
42 : ℕ#check(42:ℕ)-- a term ...ℕ : Type#check(ℕ:Type)-- ... whose type ℕ lives in `Type`2=2 : Prop#check((2=2):Prop)-- a proposition ...Prop : Type#check(Prop:Type)-- ... and `Prop` lives in `Type`
Type, the same as Type 0, is the universe of ordinary data types (ℕ, ℝ, Bool, List α, ...). Prop is the universe of propositions, statements that are true or false. Type cannot contain itself, so it lives in a larger universe Type 1, which lives in Type 2, and so on without end:
Type : Type 1#check(Type0:Type1)-- `Type 0` is `Type`Type 1 : Type 2#check(Type1:Type2)-- Type 1 : Type 2
The whole tower is captured by a single keyword Sort:
So Sort covers Prop and all the Type u, and the one rule governing the hierarchy is Sort u : Sort (u+1); in particular Prop : Type. In signatures you will often see {α : Type*}: α is a type in some universe Type u, and Lean introduces the universe variable u itself (Polymorphic functions below). Of the four steps, universes have only the first: Sort u is a type, and its terms are the types built in the rest of this chapter and in chapter 1.4.
There is deliberately no Type : Type. A universe that contains itself admits a version of Russell's paradox for types, Girard's paradox, and with it a proof of False.
A function from ℕ to ℕ is a term of the type ℕ → ℕ. In Lean the type of the value may depend on the argument; the function type is then called a dependent function type, or Π-type. The ordinary function type α → β is the Π-type (x : α) → β whose β does not depend on x; Lean treats the two as the same type:
example:(ℕ→ℕ)=((n:ℕ)→ℕ):=rfl
Formation. For types α and β, α → β is the type of functions from α to β. More generally, if β x is a type for every x : α, then (x : α) → β x is the type of functions f with f x : β x for every x.
Construction. A function is built with fun. If e is a term of type β x, in which x may occur, then fun x => e has type (x : α) → β x. Mathematics writes x ↦ x^2; Lean writes fun x => x ^ 2, or fun x ↦ x ^ 2 with the arrow ↦ (typed \mapsto).
Use. A function is applied by writing it in front of its argument: f a, without parentheses, has type β a.
Computation. Applying a function built with fun substitutes the argument: (fun x => e) a reduces to e with a in place of x. This is the β-rule of the reduction rules.
A function is usually given a name with def, writing its arguments before the :=:
def name (arguments) : resultType := body
This is short for def name : (arguments) → resultType := fun arguments => body. So the following defines double, taking one argument n : ℕ and returning 2 * n:
A pure function returns the same result for the same arguments, exactly as in mathematics. Functions of several arguments are curried: a function of two arguments is a function that takes one argument and returns another function.
A function built with fun needs no name; it can be applied on the spot:
funx=>x+1 : ℕ→ℕ#check(funx:ℕ↦x+1)-- fun x => x + 1 : ℕ → ℕ6#eval(funx:ℕ↦x+1)5-- 6funxy=>x*y : ℕ→ℕ→ℕ#check(funxy:ℕ↦x*y)-- fun x y => x * y : ℕ → ℕ → ℕ12#eval(funxy:ℕ↦x*y)34-- 12
Shorter still is the · placeholder (a centered dot, typed \cdot), which stands for an anonymous argument: (· + 10) is shorthand for fun x ↦ x + 10, and several ·· become successive arguments, so (· + ·) means fun x y ↦ x + y.
A proof of ∀ n : ℕ, n < n + 1 takes each n : ℕ to a proof of n < n + 1. It is a function as well, of the same kind as fun n => n + 1; the only difference is that the type of the value, n < n + 1, depends on n.
There are two notations for the Π-type. We write (x : α) → β x, or α → β if β does not mention x, when β x is data, and ∀ x : α, β x when β x is a proposition. The two notations denote the same type, so rfl proves them equal:
The first proof is written down directly as a term. A proof with by builds such a term as well (Tactic mode and term mode).
A dependent function whose values are data: Mathlib's ZMod n is the type ℤ/nℤ of integers modulo n (with ZMod 0 = ℤ). The function sevenMod takes n to the residue class of 7 in ℤ/nℤ. Its definition reads 7 for every n, but each value lies in a different type and is a different element there:
The numeral 7 in ZMod 5 is read modulo 5, so #eval shows the representative 2. How a numeral gets its meaning in a type is explained in Where numerals come from.
In terms of sets, a function f : (x : α) → β x chooses one element f x ∈ β x for every x. It is an element of the product \prod_{x \in \alpha} \beta(x). This is where the name Π comes from.
The argument of a function may itself be a type. The identity function takes a type α and returns the identity on α; its type (α : Type) → α → α is a Π-type, because the type of the rest depends on α:
Usually you do not want to pass the type explicitly every time, so you make it an implicit argument with braces {...}; Lean then infers it from the other arguments. The prefix @ makes the implicit arguments explicit again, for instance to see them in #check:
A definition that should work in every universe takes a universe variable. You may introduce one with the universe command, or, most commonly, write Type*, which inserts a fresh universe variable for you:
The third argument is a proof of 3 ≠ 0, here written as a tactic proof by decide in the place of a term: decide proves a statement without variables by computing whether it holds. The type (a b : ℤ) → b ≠ 0 → ℤ of safeDiv is a Π-type, because the type of the proof depends on b.
Nat, List, Option, Bool and Empty are all inductive types; Nat and Bool were dissected in the previous chapter. An inductive type is given by a list of constructors, each saying how to build a new element out of existing pieces. Declaring the natural numbers by hand reproduces exactly the structure of Nat:
Formation. The declaration introduces the type MyNat : Type. The universe of an inductive type must be large enough to hold the arguments of all its constructors.
Construction. The terms of MyNat are built with the two constructors MyNat.zero and MyNat.succ, and every element is either zero or succ n. Where Lean already knows that a MyNat is expected, the type name can be dropped and a leading dot written instead: .succ .zero for MyNat.succ MyNat.zero.
Use. A term of an inductive type is used by distinguishing which constructor built it: pattern matching, the subject of chapter 1.3. Lean translates every pattern match into the type's recursorMyNat.rec, which the declaration also introduces.
Computation. Applied to a term built by a constructor, a pattern match takes the branch for that constructor. For the recursor this is the ι-rule of the reduction rules, MyNat.rec z s (.succ n) ⟶ s n (MyNat.rec z s n), the firing we watched for Nat.
-- `MyOption α` is `none` or `some a` with `a : α`inductiveMyOption(α:Type)where|none:MyOptionα|some(a:α):MyOptionαexample:MyOptionℕ:=.some3
Here MyOption α is a type for every type α.
Lean's Option is declared in the same way, and Mathlib builds on it. The natural numbers with ∞ are ℕ with one new element added, which Option does:
defMyENat:Type:=Optionℕ
Here none plays the role of ∞. Mathlib's ℕ∞ (typed \bN\infty) is notation for ENat, defined as WithTop ℕ, and WithTop α is Option α with none read as a new largest element ⊤ (#print ENat, #print WithTop). So ℕ∞ is MyENat, and rfl sees it:
Lean's ∨ is Or, declared in the same way. It is the disjoint union for propositions: the constructor records which side the proof came from. Conjunction ∧ has one constructor with two arguments; it is a structure, and comes in Structures below.
Inductive types are the main mechanism by which new data types enter Lean, and Mathlib uses them throughout.
A structure is an inductive type with exactly one constructor, whose arguments are named fields. Many mathematical objects are of this kind. A point in the plane has an x-coordinate and a y-coordinate:
structurePointwherex:ℕy:ℕ
The declaration is essentially the same as
inductive Point where
| mk : ℕ → ℕ → Point
Use structure for a type with a single constructor with named fields (points, complex numbers, algebraic structures), and inductive for a type with several constructors (natural numbers, lists, trees, Option, Bool).
Formation. The declaration introduces the type Point : Type.
Construction. There is a single constructor, Point.mk, so both fields must be supplied: Point.mk 3 4 is a point.
Use. A field is read off with its projection: Point.x p is the x-coordinate of p : Point. A name such as Point.x, which begins with the name of a type, can also be written after a term of that type, separated by a dot: p.x means Point.x p.
Computation. A projection applied to a point built by the constructor returns the field: (Point.mk 3 4).x reduces to 3.
Like every inductive type, Point has a recursor, Point.rec. It takes a single case, a function of the fields, and the projections Point.x and Point.y are defined through it.
A value of a structure is determined by its fields: p and Point.mk p.x p.y are definitionally equal, so rfl proves it. This is the η rule of the reduction rules, here for structures. For a general inductive type there is no such rule: n : ℕ is not definitionally 0 or a successor, and to split on it you need cases.
They are the record form { x := …, y := … }, the anonymous constructor⟨...⟩ (typed \< and \>), the explicit Point.mk, and the blockwhere form, one field := value line per field, with no braces or commas. The where form is just the record form spread over several lines; it has nothing to do with the |-branches of pattern matching below (fields are field := value, not | pattern => …).
Here the target type is fixed by the : Point on the left of :=, so Lean knows which constructor { … } and ⟨…⟩ mean. When the type is not clear from the context, you can annotate the record itself:
Fields may be given default values as part of the declaration, and a value may then omit those fields:
-- the arithmetic progression a, a + d, a + 2d, ...structureArithProgwherestart:ℕ:=0step:ℕ:=1defevens:ArithProg:={step:=2}0#evalevens.start-- 0 (the default)2#evalevens.step-- 2
With both defaults, {} is the progression 0, 1, 2, … of all natural numbers.
One structure can extend another, inheriting all of its fields. A value supplies all fields, inherited and new:
structurePoint3DextendsPointwherez:ℕdefq:Point3D:={x:=1,y:=2,z:=3}1#evalq.x-- 1 (inherited from Point)3#evalq.z-- 3
Mathlib builds its algebraic structures in this way: a commutative ring extends a ring, which extends a semiring.
p2.normSq (the squared distance from the origin) works because Lean sees that p2 : Point and looks for Point.normSq. A Gaussian integer (a complex number with integer parts) gives a fuller example, data and its operations together:
To build a term, both the function and the proof must be supplied. This pattern of bundling data with properties is how Mathlib organizes mathematics: a linear map, a continuous function and a group homomorphism are all structures of this kind.
Fin n, the type of the natural numbers less than n, is a structure of this kind as well. An element consists of a natural number val together with a proof isLt that it is less than n. Lean's Prelude declares
structure Fin (n : ℕ) where
val : ℕ
isLt : val < n
and the constructor Fin.mk takes both fields:
@Fin.mk : {n:ℕ}→(val:ℕ)→val<n→Finn#check@Fin.mk-- {n : ℕ} → (val : ℕ) → val < n → Fin nexample:Fin3:=⟨2,by⊢ 2<3decideAll goals completed! 🐙⟩example(n:ℕ)(h:0<n):Finn:=⟨0,h⟩2#eval(⟨2,by⊢ 2<3decideAll goals completed! 🐙⟩:Fin3).val-- 2
Two elements of Fin n are equal when their values are, which is Fin.ext. Fin.last n is the largest element of Fin (n + 1), the pair of n and a proof of n < n + 1. Its type depends on n, so Fin.last is a dependent function in the sense of Dependent functions above:
Fin.ext needs no axiom. cases splits a and b into their fields; once the values agree, two proofs of val < n remain, and these are equal by rfl, because Lean does not distinguish proofs of the same proposition (Why Prop is special):
Mathlib calls every lemma of the form "equal if the parts are equal" .ext: Fin.ext, Prod.ext, Subtype.ext. For functions the analogous statement, funext, does not follow from splitting into fields; it is discussed in Function extensionality is a theorem.
A proof of P ∧ Q consists of a proof of P and a proof of Q. Lean's Prelude declares And as a structure with the two fields left and right, both proofs:
structure And (a b : Prop) : Prop where
intro ::
left : a
right : b
The line intro :: names the constructor And.intro instead of the default And.mk.
P ∧ Q is the pair of two proofs, as α × β is the pair of two data. The projections are h.1 and h.2, also written h.left and h.right. Where ∧ is the pair, ∨ from Inductive types is the disjoint union.
The slides for this chapter follow it section by section.
A term of an inductive type is used by asking which constructor built it. This chapter is about the functions defined in this way: by pattern matching, by recursion, and by the recursor itself. Chapter 1.1 wrote such functions on ℕ with Nat.rec by hand; here Lean writes them from equations, for every inductive type of chapter 1.2, structures included.
In chapter 1.1, myDouble was defined with the recursor Nat.rec, one argument per constructor. Pattern matching is another way to define a function on an inductive type, and the usual one: the cases are written as equations, one branch per constructor, each prefixed by |. Lean translates them into the recursor (The recursor). The function myNot on Bool in chapter 1.1 was of this kind. The factorial function on ℕ matches on whether the input is 0 or a successor n + 1:
Each branch may use the variables introduced by its pattern (here n on the right-hand side). Lean checks two things automatically:
Exhaustiveness. Every constructor of ℕ is covered (the cases 0 and n + 1 exhaust ℕ). If you forget a case, Lean complains.
Termination. The recursive call factorial n is on a strictly smaller argument than n + 1, so the recursion ends.
It works just as well for the inductive types you declare yourself. For MyNat, doubling and the conversion to ℕ are defined by matching on the two constructors:
Writing plain zero in place of .zero would fail: there is no zero in scope, only MyNat.zero. As for Point.x, for m : MyNat the name m.toNat means MyNat.toNat m.
Pattern matching is translated into the recursor for the kernel and into running code for #eval. A definition with the recursor of your own type, as in Recursion on trees, cannot be run by #eval. That is why functions are usually written by pattern matching.
Pattern matching works for any inductive type. A list is empty, or a first element followed by a list. In Lean's library (u is a universe variable, Polymorphic functions):
inductive List (α : Type u) where
| nil : List α -- written []
| cons (a : α) (l : List α) : List α -- written a :: l
infixr:67 " :: " => List.cons
syntax "[" term,* "]" : term -- simplified
macro_rules
| `([]) => `(List.nil)
| `([$a]) => `(List.cons $a List.nil)
| `([$a, $as,*]) => `(List.cons $a [$as,*])
infixr makes :: a right-associative infix operator with binding power 67, so 1 :: 2 :: [] is 1 :: (2 :: []). syntax declares the bracket form, and macro_rules rewrites it, one element at a time, into List.cons and List.nil (chapter 1.7). So [1, 2, 3] is 1 :: 2 :: 3 :: [], that is List.cons 1 (List.cons 2 (List.cons 3 List.nil)). Lean's own definition (Init/Data/List/Notation.lean) does the same, with one shortcut for lists of 64 or more elements. A function on lists has a branch for [] and one for a :: l. The pattern _ matches anything and names nothing.
-- A function on Option α: extract or use a defaultdefOption.getD'{α:Type*}(d:α):Optionα→α|none=>d|somea=>a-- A recursive function on List αdeflength'{α:Type*}:Listα→ℕ|[]=>0|_::xs=>1+length'xs
The same syntax can be used inside a term with match:
A recursive call is structural if its argument is a part of the input, that is, an argument of the constructor that built it. The numerals in the patterns stand for constructors: 0 is Nat.zero, 1 is Nat.succ Nat.zero, and n + 2 is Nat.succ (Nat.succ n). The parts of n + 2 are n + 1 and n, so both calls of fib are structural. factorial and length' are structural as well. Lean translates a structurally recursive definition into the recursor of the type (The recursor), and there is nothing to prove. So fib computes by ι, and rfl checks values:
Lean accepts a recursive definition only once it is convinced that the recursion terminates. Structural recursion is one way. The other is a measure, a natural number computed from the arguments that decreases with every call (Termination by a measure). A call that is neither is rejected:
deffail to show termination forloopwith errorsfailed to infer structural recursion:Not considering parameter n of loop:it is unchanged in the recursive callsno parameters suitable for structural recursionwell-founded recursion cannot be used, `loop` does not take any (non-fixed) argumentsloop(n:ℕ):ℕ:=loopn+1
Lean reports that the argument n is unchanged in the recursive call. Were the definition accepted, it would give loop 0 = loop 0 + 1, and subtracting loop 0 on both sides gives 0 = 1.
The recursor Nat.rec of chapter 1.1 hands the step only the value at n, but fib (n + 2) needs the values at n and at n + 1. By hand, with Nat.rec alone, one carries the pair (fib n, fib (n + 1)) along. Its type ℕ × ℕ is the type of pairs of natural numbers. In general α × β is a structure (Structures) with the two fields fst : α and snd : β; a pair is written (a, b), and its fields are p.1 and p.2. As for every structure, ⟨a, b⟩ works as well, but only where Lean already knows the type: #check ⟨1, 2⟩ fails, #check (1, 2) gives ℕ × ℕ, because (a, b) is notation for Prod.mk a b alone. Chapter 1.4 treats pairs in full.
Chapter 1.1 used the recursor Nat.rec in a non-dependent form, into a fixed result type. In general the result type may depend on the term being consumed. This dependency is recorded by a motiveT → Sort u. The figure shows how Lean builds MyNat.rec from the declaration of MyNat (chapter 1.2). The names zero and succ of the cases are added for reading; #check @MyNat.rec omits them.
How MyNat.rec is built. Each part of the declaration (top) is boxed in a colour; the arrow leads to the part of the recursor (bottom) it produces.
The case for succ receives the argument n and, because n is again of type MyNat, the value motive n already computed for it. Lean generates T.rec for every inductive declaration from its constructors, always by the same recipe:
The parameters of T, such as α in MyOption α, as implicit arguments.
The motivemotive : T → Sort u, the type of the result, which may depend on the term.
One case per constructor, in the order of the declaration. For a constructor c (a₁ : A₁) … (aₖ : Aₖ) : T the case takes the arguments a₁ … aₖ, then, for every argument aᵢ of type T itself (a recursive argument), a value of motive aᵢ, and returns a value of motive (c a₁ … aₖ).
The term t : T to be consumed; the result has type motive t.
As one picture, for T with constructors c₁, …, cₘ (parameters omitted). The arguments of c₁ are split into non-recursive ones bⱼ : Bⱼ and recursive ones rⱼ : T. For readability the non-recursive ones are listed first; in a declaration they may come in any order, and the case keeps that order.
The recursor of an arbitrary inductive type T.
With the recursor come its computation rules, one per constructor. Applied to a constructor, the recursor takes the case for it and passes it the arguments and, for each recursive argument, the recursor applied to that argument. With R := T.rec f₁ … fₘ:
For MyNat the rule for succ is MyNat.rec z s (.succ n) ⟶ s n (MyNat.rec z s n).
T.rec has no body. It is not defined by a term; the kernel adds it as a new constant, a recursor, together with these rules, and everything T.rec does is reduction by them. Applying one is ι-reduction (the reduction rules). A rule fires only when the argument is a constructor application: MyNat.rec z s t for a variable t does not reduce, which is why statements about all t need induction rather than rfl. #print shows the rules:
recursorMyNat.rec.{u} : {motive:MyNat→Sort u}→motiveMyNat.zero→((n:MyNat)→motiven→motiven.succ)→(t:MyNat)→motivetnumber of parameters: 0number of indices: 0number of motives: 1number of minors: 2rules:for MyNat.zero (0 fields): funmotivezerosucc=>zerofor MyNat.succ (1 fields): funmotivezerosuccn=>succn(MyNat.reczerosuccn)#printMyNat.rec
With a Prop-valued motive the same recursor is the induction principle: to prove a statement for every t : MyNat, prove it for zero, and prove it for succ n assuming it for n. Recursion and induction are two readings of the single primitive MyNat.rec, which is why the induction tactic and recursive definitions feel so alike. The induction tactic applies the recursor for you: one subgoal per constructor, with an induction hypothesis for each recursive argument.
List.cons has the non-recursive argument head and the recursive argument tail, so its case gets motive tail, the result for the rest of the list; read as a proof, this is the induction hypothesis. The computation rule is List.rec n c (a :: l) ⟶ c a l (List.rec n c l). The constructors of Colour have no arguments, so its cases are plain values and Colour.rec is a case distinction with three branches. MyOption.some has an argument a : α that is not recursive, so its case is a function of a and gets no value of the motive. A structure has a single constructor, so Point.rec just unpacks the fields. For an inductive type in Prop with more than one constructor, such as MyOr, the motive may only take values in Prop (Why Prop is special).
Besides T.rec, Lean defines T.casesOn, the recursor without the values at the recursive arguments. It takes t before the cases:
How MyNat.casesOn is built. As for MyNat.rec, but the recursive argument n gives no value motive n.
MyNat.casesOn t z s only asks which constructor built t: the result is z if t is zero, and s n if t is succ n. There is no recursion. It is an ordinary definition, built from the recursor: MyNat.casesOn t z s is MyNat.rec z (fun n _ => s n) t. For ℕ the same is Nat.casesOn:
Pattern matching is compiled to casesOn. Lean writes the patterns with constructors and splits the argument by its constructor, zero or succ m, and splits m again where a pattern requires it. For the patterns 0, 1, n + 2 of fib this gives two nested case splits:
fun x => Nat.casesOn x (case 0) -- x = zero
(fun m => Nat.casesOn m (case 1) -- x = succ m, m = zero
(fun n => (case n + 2))) -- x = succ (succ n)
The pattern 1 is read in two steps: the outer split finds succ m, the inner split finds m = zero. Lean stores this term as fib.match_1; its cases h_1, h_2, h_3 are the right-hand sides of the three patterns:
@[instance_reducible] deffib.match_1.{u_1} : (motive:ℕ→Sort u_1)→(x:ℕ)→(Unit→motive0)→(Unit→motive1)→((n:ℕ)→motiven.succ.succ)→motivex :=funmotivexh_1h_2h_3=>Nat.casesOnx(h_1())funn=>Nat.casesOnn(h_2())funn=>h_3n#print`fib.match_1` refers to an auto-generated auxiliary declaration. These are not stable across refactors; consider using a different approach.Note: This linter can be disabled with `set_option linter.auxLemma false`fib.match_1
Every leaf of this tree must be reached by one of the patterns. With the line for 1 missing, the case Nat.succ Nat.zero is reached by none:
The error is "Missing cases: (Nat.succ Nat.zero)". A pattern that can never be reached, because earlier patterns already cover it, is an error as well ("Redundant alternative").
A structural call may be on any part of the input, and a definition may call itself on several parts at once. Binary trees whose nodes carry natural numbers:
BinTree is the type of all finite binary trees of this kind, of any shape; each element is one particular tree. Both constructors build a whole tree:
leaf is the tree that consists of a single leaf. It carries no number. Inside a larger tree it marks the end of a branch, so .leaf on its own is the empty tree.
node l a r is the tree whose root carries the number a, with left subtreel and right subtreer. Both are again whole trees, possibly leaf.
So the numbers sit at the nodes, and every node has exactly two subtrees. Where a branch stops, the subtree is leaf. All leaves are the same term .leaf. A tree is a term, and two leaves of one tree differ only in their position, as the two entries of the pair (1, 1) do: .node .leaf 4 .leaf contains the subtree .leaf twice, once on the left and once on the right. In the same way .node t 5 t contains the tree t twice. Two trees are equal when they have the same shape and the same numbers at the same places. Putting the numbers into the leaves instead, leaf (a : ℕ) : BinTree, gives another type; MyTree in Strict positivity is declared that way.
Three elements of BinTree. Circles are nodes and carry their number, squares are leaves and carry nothing.
The height counts the nodes on the longest path from the root down to a leaf. It recurses on both subtrees:
The recursor of BinTree follows the recipe of The recursor. The case for node receives the three arguments of the constructor and, for the two subtrees l and r, the values motive l and motive r:
@BinTree.rec : {motive:BinTree→Sort u_1}→motiveBinTree.leaf→((l:BinTree)→(a:ℕ)→(r:BinTree)→motivel→motiver→motive(l.nodear))→(t:BinTree)→motivet#check@BinTree.rec-- {motive : BinTree → Sort u} →-- motive .leaf → -- leaf case-- ((l : BinTree) → (a : ℕ) → (r : BinTree) →-- motive l → motive r →-- motive (.node l a r)) → -- node case-- (t : BinTree) → motive t
With the constant motive fun _ => ℕ this is recursion, for instance the sum of all numbers in a tree:
Lean evaluates a definition in two ways. The compiler translates it into a program, and #eval runs that program. The kernel reduces the term with the reduction rules, and rfl uses the kernel. The keyword noncomputable tells Lean not to compile a definition. Nothing else changes: the definition has the same type and the same value, rfl and all proofs work as before, and only #eval is unavailable. Here the keyword is needed because the compiler does not support the recursors of your own types (for Nat it has special support). With a Prop-valued motive, BinTree.rec is induction on trees with two induction hypotheses, one for each subtree.
When a recursive call is not on a part of the input, Lean cannot translate the definition structurally and looks for a measure. It then translates the definition into WellFounded.fix and needs a proof that the measure decreases. Often it finds the measure and the proof on its own. In log2 the argument shrinks from n to n / 2. This holds only for n ≥ 1; for n = 0 the call would be log2 0 again. The if excludes this case: the recursive call stands in the branch where 2 ≤ n, and Lean uses this condition to prove n / 2 < n.
Without the if, Lean is left with the goal n / 2 < n for an arbitrary n, which is false for n = 0, and rejects the definition:
deffail to show termination forlog2'with errorsfailed to infer structural recursion:Cannot use parameter n:failed to eliminate recursive applicationlog2'(n/2)failed to prove termination, possible solutions: - Use `have`-expressions to prove the remaining goals - Use `termination_by` to specify a different well-founded relation - Use `decreasing_by` to specify your own tactic for discharging this kind of goaln:ℕ⊢ n/2<nlog2'(n:Nat):Nat:=1+log2'(n/2)
Cantor's enumeration of ℕ × ℕ runs through the pairs diagonal by diagonal: (0, 0); (0, 1), (1, 0); (0, 2), (1, 1), (2, 0); and so on. pairIndex m n is the position of (m, n) in this list. Within a diagonal it steps back from (m + 1, n) to (m, n + 1); from the first pair (0, n + 1) of a diagonal it steps back to the last pair (n, 0) of the previous one.
Cantor's enumeration of ℕ × ℕ. The point (m, n) carries pairIndex m n; the arrows run along a diagonal.
Here Lean needs help. No argument decreases in both recursive calls, and the sum m + n stays the same in the third line. Without the last two lines of the definition Lean reports "Could not find a decreasing measure". The measure is the pair (m + n, m) : ℕ × ℕ: first the diagonal m + n, then the position m on it. Pairs are compared lexicographically: (a, b) is smaller than (c, d) if a < c, or if a = c and b < d. termination_by names the measure; m n => names the two arguments, which the patterns leave unnamed. decreasing_by proves that the measure decreases. There is one goal for each recursive call, and all_goals applies the same tactics to both: rw [Prod.lex_def] replaces the lexicographic order by its definition, and omega, a tactic that proves linear arithmetic over ℕ and ℤ, finishes.
That pairs are compared lexicographically is not written in the definition. Lean takes the order from the type of the measure, by instance search for the class WellFoundedRelation (typeclasses are the subject of chapter 1.6). On ℕ the order is <; on a product it is Prod.lex, built from the orders on the two factors. The command #synth C runs this search for the class C and prints the instance it finds, or an error if there is none:
Prod.instWellFoundedRelation#synthWellFoundedRelation(ℕ×ℕ)-- Prod.instWellFoundedRelation, defined as Prod.lex
Sometimes Lean finds the measure but cannot prove that it decreases. Which measure it found, termination_by? prints; for the logarithm to base b below it is termination_by n. Lean then has to show n / b < n. For b = 2 this is linear arithmetic, which Lean does by itself; for a variable b it is not, and Lean stops with this goal. decreasing_by supplies the proof, here with the library theorem Nat.div_lt_self : 0 < n → 1 < k → n / k < n. The proof needs the condition of the if by name, so the if is dependent: in if h : c then a else b, the proof h : c is available in a, and a proof of ¬c in b. Here h.1 : 2 ≤ b gives 1 < b, and 0 < n follows from h by omega:
The theory behind well-founded recursion, what makes a relation well-founded and why < on Nat qualifies, is in Accessibility and well-founded relations. If decreasing_by is left out, Lean tries a standard tactic, decreasing_tactic, which handles the simple cases on its own.
Functions or types that refer to each other are declared together in a mutual … end block; see the Lean Language Reference.
1.3.6. Proving things about recursive definitions🔗
A structurally recursive definition is translated into the recursor, and the recursor computes by ι. So rfl and #eval see through it, even with a variable in the argument:
A definition by well-founded recursion does not compute in this way. #eval runs it, but the kernel does not unfold WellFounded.fix, so rfl and decide fail even on closed terms:
example:log216=4:=Type mismatchrflhas type?m.7=?m.7but is expected to have typelog216=4rfl
Instead Lean proves an equation lemma for every definition, here log2.eq_1, which states the defining equation. Proofs use it through rw [log2], unfold log2 or simp [log2]:
log2.eq_1(n:ℕ):log2n=if2≤nthen1+log2(n/2)else0#checklog2.eq_1-- log2.eq_1 (n : ℕ) : log2 n =-- if 2 ≤ n then 1 + log2 (n / 2) else 0example:log216=4:=by⊢ log216=4simp[log2]All goals completed! 🐙example(n:ℕ)(h:2≤n):log2n=1+log2(n/2):=byn:ℕh:2≤n⊢ log2n=1+log2(n/2)rw[log2n:ℕh:2≤n⊢ (if2≤nthen1+log2(n/2)else0)=1+log2(n/2)]n:ℕh:2≤n⊢ (if2≤nthen1+log2(n/2)else0)=1+log2(n/2)simp[h]All goals completed! 🐙
Proofs by induction that follow the recursion of a function, one case per branch, are done with fun_induction (induction).
The recursor hands the case for succ n one value, the value at n. A structurally recursive definition may call itself on any part of the input: fib (n + 2) calls fib (n + 1) and fib n. Lean's translation closes this gap. It passes the step a table of the values at all smaller arguments, built from the recursor in one pass (the constant Nat.brecOn; #print fib shows it), and replaces every recursive call by a lookup in this table. This is called course-of-values recursion. How the table is built is Project 7.
#eval does not use this translation. The compiler runs fib as written, and every call makes two more, so the running time grows like fib n itself, by a factor of about 1.6 per step. Carrying the pair by hand, as in fibPair (Structural recursion), needs one step per number:
#eval fib 30 -- 0.6 s
#eval fib 32 -- 1.7 s: about 7 million calls
#eval (fibPair 32).1 -- immediate: 32 steps
#eval (fibPair 10000).1 -- immediate, 2090 digits
With a Prop-valued motive the table holds proofs: the statement for all smaller arguments. A theorem proved by pattern matching with recursive calls is translated just like a definition. This is the form of strong induction that structural recursion gives:
Not every inductive declaration is accepted. A constructor may mention the type being defined, but only positively. The arrow here is the → of a function type: in α → β the type α of the inputs stands to the left of the arrow, the type β of the values to the right. Strictly positive means that in the type of an argument of a constructor, the type being defined never stands to the left of an arrow. The type of the constructor itself does not count: every constructor of a type T ends in → T, and only the arguments before that last arrow are checked. An example that is accepted is a type of infinitely branching trees:
MyTree is a type, and each of its elements is a tree. The constructors say what stands at the root. leaf a is the tree that consists of a single leaf, carrying the number a. node f is the tree whose root is a node with one subtree f n for every n : ℕ. Each f n is again a whole tree; where it is leaf n, it is a leaf of the big tree. The argument f of node has type ℕ → MyTree, and there MyTree stands to the right of →, so the declaration is accepted.
One element of MyTree, the last tree above. Circles are nodes, squares are leaves; the edge to the subtree f n is labelled n.
Every tree has a root, and every path from the root downwards ends in a leaf after finitely many steps: an element of an inductive type is built by constructors, from the bottom up. A tree that goes on downwards forever is not an element of MyTree. This is what makes structural recursion work, for instance for the function that descends into the subtree f 0 until it meets a leaf. Only the width is infinite. The trees can be built in stages: first all leaf a, then all node f whose subtrees are leaves, then all node f whose subtrees come from the first two stages, and so on. The finite stages do not exhaust MyTree. The depth can be unbounded: in MyTree.unbounded the path through the subtree n has length n + 1, so every path ends, but there is no largest depth. This tree uses subtrees from every finite stage and lies on none of them, and a height with values in ℕ cannot be defined.
The leaf case is what gets the type off the ground. Positivity constrains only whereMyTree may occur, not whether the type has any elements: drop leaf, and the declaration is still accepted, but no tree can ever be built, because every node already demands a whole family ℕ → MyTree of subtrees. The type is then empty, like Empty. A finitely branching tree would be node (l r : MyTree) : MyTree, where MyTree occurs directly rather than inside a function.
But a constructor that stores a function out of the type is rejected. The argument f of Bad.mk has type Bad → False, and there Bad stands to the left of →:
inductive Bad where
| mk (f : Bad → False) : Bad
-- error: (kernel) arg #1 of 'Bad.mk' has a non positive
-- occurrence of the datatypes being declared
The rejection is not pedantry: were Bad allowed, one could prove False. Every b : Bad has the form Bad.mk f, so pattern matching gives a function unmk that undoes mk: it takes Bad.mk f apart and returns f. Such a function exists for every type with a single constructor; it is just a match, and match comes with every inductive type. So nothing can be forbidden after the fact, only the declaration itself. Apply the stored function to b itself:
def unmk : Bad → (Bad → False) | .mk f => f
def neg (b : Bad) : False := unmk b b
so neg : Bad → False. Then Bad.mk neg : Bad, and neg (Bad.mk neg) : False is a closed proof of False; it even loops, neg (Bad.mk neg) ⟶ unmk (Bad.mk neg) (Bad.mk neg) ⟶ neg (Bad.mk neg). Read as logic: mk and unmk together say Bad ↔ ¬Bad, and the two definitions above are the propositional proof that P ↔ ¬P implies False. Lean checks the argument once mk and unmk are given as hypotheses instead of being declared:
Read in sets, the declared type is a set X that satisfies an equation X = F(X). Here F(X) is everything the constructors build from arguments in X, and the equation says that an element of the type is exactly one of these things. False is the empty set.
declaration
equation
ℕ
X = {0} ⊔ X
MyTree
X = ℕ ⊔ (ℕ → X)
Bad
X = (X → ∅)
The type exists if the equation has a solution, a fixed point X = F(X). Whether it has one depends on where X stands. ℕ → X grows with X: a function into a smaller set is also a function into a larger one. X → ∅ shrinks when X grows. So if X occurs only to the right of →, the map F is monotone: X ⊆ Y gives F(X) ⊆ F(Y).
A monotone F has a fixed point, reached by the stages described for MyTree above. Put X₀ = ∅, X₁ = F(X₀), X₂ = F(X₁), …, and take unions at limit stages. By monotonicity the sets grow, and the stages continue transfinitely until nothing new is added; for MyTree this happens at the first uncountable ordinal, because each node has only countably many subtrees. The result is a set with X = F(X). The constructors are maps into it, and the recursor is recursion over the stage at which an element first appears. A strictly positive declaration therefore adds only something that already exists in set theory, and cannot produce a contradiction. This is the set-theoretic semantics of inductive definitions: Aczel (1977)Peter Aczel, 1977. “An Introduction to Inductive Definitions”. In Handbook of Mathematical Logic (J. Barwise, ed.), North-Holland, 739–782. for monotone inductive definitions in general, Dybjer (1991)Peter Dybjer, 1991. “Inductive Sets and Families in Martin-Löf's Type Theory and Their Set-Theoretic Semantics”. In Logical Frameworks (G. Huet, G. Plotkin, eds.), Cambridge University Press, 280–306. for inductive types in Martin-Löf's type theory, and Werner (1997)Benjamin Werner, 1997. “Sets in Types, Types in Sets”. In Theoretical Aspects of Computer Software (TACS 1997). (Lecture Notes in Computer Science 1281) for the Calculus of Inductive Constructions, with a model in ZFC plus inaccessible cardinals. For the type theory Lean implements, the same construction is part of the model of Carneiro (2019)Mario Carneiro, 2019. “The Type Theory of Lean”. In MSc thesis, Carnegie Mellon University., with the gap described in Why Prop is special.
For Bad there is no solution. X → ∅ has one element (the empty function) if X is empty, and none otherwise, so X = (X → ∅) fails either way: this is Bad ↔ ¬Bad. The stages do not help, because F is not monotone; they alternate between ∅ and a one-element set. For a negative occurrence with values in Bool, mk (f : Bad' → Bool) : Bad', the set X would contain a copy of X → Bool, its power set, which Cantor's theorem rules out. The self-application unmk b b is Cantor's diagonal.
The word strictly matters. In mk (f : (X → Bool) → Bool) : X the type X stands to the left of two arrows, and the two reversals cancel, so F is monotone. But F(X) is then a double power set, again too large to fit into X, and together with the impredicative Prop such a declaration yields a proof of False (Coquand and Paulin-Mohring, 1990)Thierry Coquand and Christine Paulin-Mohring, 1990. “Inductively Defined Types”. In COLOG-88. (Lecture Notes in Computer Science 417). Lean therefore requires that X stand to the left of no arrow at all.
Chapter 1.2 treated function types, inductive types and structures. This chapter treats dependent pairs and subtypes, whose terms bundle a value with data or a proof about it. Then come type families, functions whose values are types; indexed families and inductive predicates, type families defined by constructors; the logical connectives, which are these type formers with values in Prop; and quotients, types of equivalence classes. Each type former is again described in the four steps Formation, Construction, Use and Computation; a table at the end collects them.
The slides for this chapter follow it section by section.
A dependent pair consists of a first component a : α and a second component b : β a whose type depends on a.
Formation. If β x is a type for every x : α, the Σ-type(x : α) × β x, also written Σ x : α, β x, is the type of these pairs. If β does not depend on x, it is the product α × β.
Construction. The pair is built with ⟨a, b⟩, or (a, b) for the product.
Use. The components are read off with the projections .1 and .2, also called .fst and .snd.
Computation.⟨a, b⟩.1 reduces to a and ⟨a, b⟩.2 to b. A pair is determined by its components: p = (p.1, p.2) holds by rfl.
The Σ-type is not a new primitive but a structure with two fields:
structureSigma.{u, v}{α:Type u}(β:α→Type v):Type (max u v)number of parameters: 2fields:Sigma.fst : αSigma.snd : βself.fstconstructor:Sigma.mk.{u, v}{α:Type u}{β:α→Type v}(fst:α)(snd:βfst):Sigmaβ#printSigmadefaPair:(n:ℕ)×Fin(n+1):=⟨3,Fin.last3⟩3#evalaPair.1-- 3aPair.snd : Fin(aPair.fst+1)#checkaPair.2-- aPair.2 : Fin (aPair.fst + 1)example(p:ℕ×ℕ):p=(p.1,p.2):=rfl
In terms of sets, the pairs ⟨a, b⟩ with a fixed a form the piece \{a\} \times \beta(a), and the Σ-type is the disjoint union of these pieces, \coprod_{x \in \alpha} \beta(x). Counting shows the difference to the Π-type: the Σ-type has \sum_x |\beta(x)| elements, the Π-type \prod_x |\beta(x)|. In Lean, Fintype.card α is the number of elements of a finite type α, and the tactic decide proves the two equations below by computing both sides:
If β does not depend on x, all pieces are equal, and the Σ-type is the product α × β: the sum of |\alpha| equal summands |\beta|. The notation × for the dependent pair is named after this special case.
non-dependent
dependent
in sets
for propositions
α → β
(x : α) → β x
\prod_x \beta(x)
∀ x, P x
α × β
(x : α) × β x
\coprod_x \beta(x)
∃ x, P x
The last column is taken up in Propositions as types below. ∃ is not literally a Σ-type: it forgets which witness was given.
A subtype consists of the elements of a type α that satisfy a predicate P : α → Prop. It is a structure with two fields, an element and a proof:
structure Subtype {α : Sort u} (p : α → Prop) where
val : α
property : p val
Formation.{x : α // P x} is notation for Subtype P.
Construction.⟨a, h⟩, short for Subtype.mk a h, with a : α and h : P a.
Use.s.val : α is the element, s.property : P s.val the proof.
Computation.⟨a, h⟩.val reduces to a.
A subtype is the analogue of the Σ-type in which the second component is a proof rather than data. In Lean any two proofs of the same proposition are equal (proof irrelevance, built into the type theory; see Why Prop is special for reference). So two elements of a subtype are equal as soon as their first components are, which is Subtype.ext:
example(ab:{n:ℕ//0<n})(h:a.val=b.val):a=b:=Subtype.exth-- The type of natural numbers greater than 5defBigNat:Type:={n:ℕ//n>5}defseven:BigNat:=⟨7,by⊢ 7>5decideAll goals completed! 🐙⟩7#evalseven.val-- 7
Subtype is one structure for all predicates, so its functions, such as Subtype.ext, apply to every subtype at once, and Lean converts an element of {x : α // P x} to an element of α by itself wherever one is expected (a coercion; see Coercions for reference). A structure of your own with the same two fields is a new type. Fin n is of this kind: it carries the same data as {i : ℕ // i < n}, and Mathlib has a bijection between the two, but the two types are different. The separate type lets Fin n have operations of its own, such as arithmetic mod n.
This is how many mathematical objects are defined in Mathlib. For example, the type of prime numbers could be defined as {n : ℕ // Nat.Prime n}.
A subtype is closely related to, but distinct from, a sets : Set α: a set selects elements of α (which keep their type α), whereas the subtype {x : α // P x} is a new type. The relationship is spelled out in the chapter on sets and types.
A type family is a function that returns a type, such as Fin : ℕ → Type. It is not a type former of its own but a function in the sense of chapter 1.2, whose values are types. The codomain of a Π-type and the second component of a Σ-type are type families:
-- A simple type family indexed by BooldefBoolFamily:Bool→Type|true=>ℕ|false=>String-- Dependent function using the type familydefboolFamilyExample:(b:Bool)→BoolFamilyb|true=>(42:ℕ)|false=>("hello":String)
In mathematical formalization, type families appear everywhere. For instance, the fiber of a function f : α → β over a point b : β is the subtype {a : α // f a = b}, which is a type family indexed by β.
-- The fiber of a function as a type familydeffiber(f:ℕ→ℕ)(b:ℕ):Type:={a:ℕ//fa=b}-- An element of the fiber of (· * 2) over 10deffiberExample:fiber(·*2)10:=⟨5,rfl⟩
Vectors. Vectors are the standard example: a vector of length n with entries in α is a function Fin n → α, where Fin n is the type with n elements. Mathlib writes ![a, b, c] for the function on Fin 3 with values a, b, c.
-- A vector of 3 natural numbers, as a function on Fin 3defmyVec:Fin3→ℕ:=![10,20,30]10#evalmyVec0-- 1020#evalmyVec1-- 2030#evalmyVec2-- 30
The advantage of this representation is that indexing is always safe: you cannot access index 5 of a 3-element vector, because 5 is not a term of type Fin 3. The type system prevents out-of-bounds errors at compile time.
Matrices. Matrices are a natural extension. An m × n matrix with entries in α can be represented as a function Fin m → Fin n → α, or equivalently as Matrix (Fin m) (Fin n) α in Mathlib:
-- A 2×3 matrix of natural numbersdefmyMatrix:Fin2→Fin3→ℕ:=![![1,2,3],![4,5,6]]2#evalmyMatrix01-- 26#evalmyMatrix12-- 6
In Mathlib, matrix multiplication is only defined when the dimensions match. If A is an m × n matrix and B is an n × p matrix, then A * B is an m × p matrix. The dependent types enforce that the inner dimensions agree — a dimension mismatch is a type error, caught at compile time.
A type family can also be declared with inductive. Then the constructors decide, for each value of the argument, which elements the type has. The standard example is the type of lists of length n:
The two arguments play different roles. α, written before the colon, is a parameter: it is the same in every constructor, and every constructor returns a Vec α _. The ℕ after the colon is an index: each constructor chooses its value, nil the index 0 and cons the index n + 1. MyOption α in chapter 1.2 had a parameter and no index.
Formation.Vec α n is a type for every α and n; Vec α : ℕ → Type is a type family.
Construction. The constructors, with the indices they fix: Vec.cons 1 (Vec.cons 2 .nil) : Vec ℕ 2.
Use. Pattern matching, where only the constructors whose index fits are possible.
Computation. As for every inductive type, a match on a constructor takes its branch (ι).
The Use step is where indices pay off. The first element of a vector of length n + 1 needs no case for nil, because nil has index 0, which is not of the form n + 1:
Inductive predicates. If the family lands in Prop, the constructors are the rules by which a statement may be proved, and nothing else proves it. The even numbers:
A hypothesis h : MyEven k is used with cases h, which produces one goal for each constructor whose index can equal k. For k = 1 there is none, since 0 ≠ 1 and n + 2 ≠ 1, so cases closes the goal. For k = n + 2 only add_two remains, and cases hands over its argument:
Mathlib defines Even n differently, as ∃ r, n = r + r. But ≤ on ℕ and equality itself are inductive predicates of exactly this kind:
protected inductiveNat.le : ℕ→ℕ→Propnumber of parameters: 1constructors:Nat.le.refl : ∀{n:ℕ},n.lenNat.le.step : ∀{nm:ℕ},n.lem→n.lem.succ#printNat.leinductiveEq.{u_1} : {α:Sort u_1}→α→α→Propnumber of parameters: 2constructors:Eq.refl : ∀{α:Sort u_1}(a:α),a=a#printEq
Nat.le n has the constructors refl : n ≤ n and step : n ≤ m → n ≤ m + 1. Eq a has the parameter a, one index, and the single constructor Eq.refl a : a = a. So for h : a = b, cases h leaves only the case in which the index b is a: it replaces b by a everywhere. That is what rewriting with an equation rests on.
A proposition P : Prop is a type, and a proof of P is a term h : P. A proposition is proved when a term of it has been built. The logical connectives are not added to Lean separately: they are the type formers of this chapter and of chapter 1.2, with values in Prop. This reading of propositions as types and proofs as terms is the Curry-Howard correspondence (Some history).
For propositions P and Q, P → Q is a function type like any other, and a proof of P → Q is a function that takes a proof of P to a proof of Q. Modus ponens is function application, and chaining two implications is composition. In tactic mode, intro builds the fun and exact supplies the application (Tactic mode and term mode):
A proof of ∀ x : α, P x takes each x : α to a proof of P x: it is a dependent function (Function types and Π-types). Negation is defined from implication: ¬P is P → False.
Both are inductive types, met in chapter 1.1: True has the one constructor True.intro, False has none. So no term of False can be built from nothing. A match on h : False needs no branch, since there is no constructor to cover; nomatch h is this empty match. The result may have any type, which is ex falso quodlibet, available as False.elim:
P ∧ Q is notation for And P Q, the structure with two proof fields from chapter 1.2.
Formation.P ∧ Q. Construction.⟨hP, hQ⟩, short for And.intro hP hQ. Use. The projections h.1 and h.2, also h.left and h.right. Computation.⟨hP, hQ⟩.1 reduces to hP. It is the product α × β, for propositions.
P ∨ Q is notation for Or P Q, the inductive type with two constructors from chapter 1.2.
Formation.P ∨ Q. Construction.Or.inl hP from hP : P, or Or.inr hQ from hQ : Q. Use. Pattern matching with one branch per constructor, also available as Or.elim; in tactic mode obtain hP | hQ := h. Computation. A match on a constructor takes its branch.
This is the disjoint union of P and Q, with one difference: the match may only prove propositions. A function P ∨ Q → Bool that tells which side holds is rejected; Why Prop is special gives the reason.
∃ x, P x is notation for Exists P, an inductive type with one constructor that takes a witness and a proof:
inductiveExists.{u} : {α:Sort u}→(α→Prop)→Propnumber of parameters: 2constructors:Exists.intro : ∀{α:Sort u}{p:α→Prop}(w:α),pw→Existsp#printExists
Formation.∃ x : α, P x. Construction.⟨a, h⟩ with a : α and h : P a. Use. Pattern matching, which gives a witness and a proof; in tactic mode obtain ⟨x, hx⟩ := h. Computation. A match on ⟨a, h⟩ takes its branch.
A proof of ∃ x, P x is a pair like an element of the Σ-type or of the subtype{x : α // P x}. The difference is the universe. The subtype lives in Type, and its witness can be read off and computed with. ∃ lives in Prop, and as for ∨ the match may only prove propositions: the witness can be used inside proofs, but not to compute data.
Counting makes the difference visible. Any two proofs of a proposition are equal, so a proposition counts as 0 if false and 1 if true. The Σ-type has \sum_x |P(x)| elements, one for each witness. ∃ x, P x keeps only whether this sum is positive, that is, whether someP x holds. In the same way \prod_x |P(x)| is positive exactly if everyP x holds, which is ∀. ∃ is the propositional truncation of the Σ-type: it forgets which witness was given. Getting a witness back needs the axiom of choice (chapter 1.5).
Use ∃ when only the existence matters, which is the usual case in mathematics, and a subtype when the witness is needed.
The last way to form a type, after universes, function types and inductive types, is the quotient. Given a type α and a relation r : α → α → Prop, the type Quot r glues together elements that r relates: α seen up to r. This makes ℝ as Cauchy sequences up to equivalence an actual construction (chapter 2.1). Multiset α (lists up to reordering) is a quotient in Mathlib. ℤ, ℚ and ℤ/nℤ are quotients in mathematics, but Lean defines them through normal forms instead: Int is an inductive type with the constructors ofNat n and negSucc n (for -(n + 1)), Rat is a structure of a numerator and a denominator with proofs that the fraction is reduced, and ZMod n is Fin n for n > 0.
Quot is not defined by a declaration, the way Nat or Prod are. It is a primitive of the kernel, like Prop: #print Quot answers "Quotient primitive". Lean adds four constants and one computation rule, and the four steps below describe exactly these:
Quot : {α : Sort u} → (α → α → Prop) → Sort u
Quot.mk : (r : α → α → Prop) → α → Quot r
Quot.lift : (f : α → β) →
(∀ a b, r a b → f a = f b) → Quot r → β
Quot.ind : (∀ a, P (Quot.mk r a)) → ∀ q : Quot r, P q
Formation.Quot r is a type.
Construction.Quot.mk r a is the class of a : α.
Use.Quot.lift f h defines a function out of the quotient from a function f : α → β, but only together with a proof h that f respects r, that is ∀ a b, r a b → f a = f b. This is the mathematician's "check that this is well-defined". Quot.ind proves a property of every element of the quotient by checking it on the classes Quot.mk r a.
Computation.Quot.lift f h (Quot.mk r a) reduces to f a.
@Quot.mk : {α:Sort u_1}→(r:α→α→Prop)→α→Quotr#check@Quot.mk-- (r : α → α → Prop) → α → Quot r@Quot.lift : {α:Sort u_1}→{r:α→α→Prop}→{β:Sort u_2}→(f:α→β)→(∀(ab:α),rab→fa=fb)→Quotr→β#check@Quot.lift-- (f : α → β) → (∀ a b, r a b → f a = f b) →-- Quot r → β@Quot.ind : ∀{α:Sort u_1}{r:α→α→Prop}{β:Quotr→Prop},(∀(a:α),β(Quot.mkra))→∀(q:Quotr),βq#check@Quot.indexample(r:Nat→Nat→Prop)(f:Nat→Nat)(h:∀ab,rab→fa=fb)(a:Nat):Quot.liftfh(Quot.mkra)=fa:=rfl
One property is missing from the four steps: related elements should have the same class. It does not follow from the four constants. They all hold for Quot r := α with Quot.mk r a := a and Quot.lift f h := f, where nothing is glued and Quot.mk r a ≠ Quot.mk r b for a ≠ b. So Lean adds the property as an axiom, a constant that is assumed without proof:
@Quot.sound : ∀{α:Sort u_1}{r:α→α→Prop}{ab:α},rab→Quot.mkra=Quot.mkrb#check@Quot.sound-- r a b → Quot.mk r a = Quot.mk r b'Quot.sound' depends on axioms: [Quot.sound]#printaxiomsQuot.sound-- [Quot.sound]
#print axioms name lists the axioms that a constant depends on. With the axiom, Quot r is the quotient of α by the equivalence relation generated by r: Quot.mk r a = Quot.mk r b holds exactly when a and b are connected by a finite chain of r-steps, in either direction (Mathlib's Quot.eqvGen_exact and Quot.eqvGen_sound). So r need not be an equivalence relation. In practice one usually goes through Quotient, a thin wrapper of Quot for a relation that is an equivalence relation; such a relation, bundled with the proof that it is one, is called a Setoid.
Two functions that agree at every point are equal. This is funext, and in Lean it is not an axiom but a theorem: it follows from Quot.sound and the computation rule. Form the quotient of the function space α → β by pointwise equality. There f and g have the same class by Quot.sound. Evaluation at a point x is well defined on the quotient, because functions that agree pointwise have the same value at x; with Quot.lift it turns a class back into a function.
rfl proves hf because Lean computes the right side until it is f. The computation rule of the quotient, followed by that of functions, gives Quot.lift (fun f => f x) _ (Quot.mk eqv f) ⟶ (fun f => f x) f ⟶ f x, and the η-rule gives fun x => f x ≡ f. So the right side of hf is f by definition; the same holds for hg. After rw [hf, hg] the two sides differ only in Quot.mk eqv f and Quot.mk eqv g, and rw [hq] makes them equal. The only axiom used is Quot.sound. The proof is for functions α → β; Lean's funext treats dependent functions in the same way. The rules are listed in The reduction rules in chapter 1.1.
The rfl needs the computation rule to hold by definition. A quotient built by hand, as a type of equivalence classes with Classical.choice picking a representative, satisfies it only as a proved equation, and the rfl fails. This is one reason why Quot is a primitive of the kernel and not a definition.
ℤ/2ℤ is the quotient of ℤ by the relation "same parity", that is, same remainder mod 2. In Mathlib it is ZMod 2, the case n = 2 of the ZMod n from Dependent functions. Built by hand:
-- a and b have the same remainder mod 2defSameParity(ab:ℤ):Prop:=a%2=b%2defParity:Type:=QuotSameParitydefParity.mk(a:ℤ):Parity:=Quot.mkSameParityaexample:Parity.mk7=Parity.mk1:=Quot.soundrfl
Quot.sound turns the proof 7 % 2 = 1 % 2, which is rfl, into the equality of the two classes. A function out of Parity needs a proof that it is well defined. For the remainder of a class this proof is the relation itself:
The map to Mathlib's ZMod 2 sends the class of a to a read in ZMod 2. It is well defined by the library theorem ZMod.intCast_eq_intCast_iff', which says that two integers are equal in ZMod 2 exactly when they have the same remainder mod 2:
Mathlib itself does not define ZMod 2 as a quotient. ZMod is defined by pattern matching on its argument: ZMod 0 is ℤ, and ZMod 2 is Fin 2. This makes it computable: #eval and decide work on it. ZMod 2 is still isomorphic to the quotient of ℤ by the ideal 2ℤ; see Quotient structures in chapter 2.5 for reference.
Here e[x := a] is e with a in place of x. Universes have only a formation step, Sort u. The next chapter states these steps as the rules of Lean's type theory.
Types were introduced to stop a contradiction. Russell's set R = \{x : x \notin x\} broke Frege's Grundgesetze der Arithmetik in 1902 (Introduction). Russell's repair of 1908 gave every object a type and let a type apply only to objects of lower type, so that x ∈ x is not false but not a statement at all. Zermelo's repair of the same year instead restricts which sets exist and leaves x ∈ x a formula. Mathematics followed Zermelo; proof assistants follow Russell, because a type checker can decide before any question of truth whether an expression means anything.
Principia Mathematica (1910 to 1913) is written in Russell's theory. Leon Chwistek and Frank Ramsey simplified it in the 1920s to the simple theory of types, and Alonzo Church turned that into a calculus in 1940, the simply typed lambda calculus on which Isabelle/HOL still rests. That propositions can be read as types and proofs as terms is the Curry-Howard correspondence: Haskell Curry observed in 1934 that the types of the combinators of combinatory logic are the axioms of propositional logic, and William Howard extended this in 1969 (published 1980) to natural deduction and the simply typed lambda calculus. Dependent types, in which a type may mention a term, came with de Bruijn's Automath (1967) and Martin-Löf's type theory (1971). Coquand and Huet added impredicative quantification in the Calculus of Constructions (1985), and Paulin-Mohring added inductive types (1990). Lean's type theory is a variant of the result, the Calculus of Inductive Constructions. Three times the same thing happened: a system let an object be applied to itself, a contradiction followed, and types forbade it. In Lean the ban is visible as Type 0 : Type 1 : Type 2 : ....