Interactive Theorem Proving using Lean, Winter 2026/27

1. Lean and its type theory🔗

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.)

1.1. Introduction🔗

We begin with the natural numbers, ℕ (notation for the type Nat), as a running example.

1.1.1. The natural numbers🔗

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 recursor Nat.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):

example (C : Type) (base : C) (step : Nat → C → C) : Nat → C := fun n ↦ Nat.rec base step n

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.rec computes. 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:

def step (_ j : Nat) : Nat := j + 2 def myDouble (n : Nat) : Nat := Nat.rec 0 step n -- myDouble 2 -- ⟶ Nat.rec 0 step 2 -- δ: unfold myDouble -- ⟶ step 1 (Nat.rec 0 step 1) -- ι on succ, then δβ -- ⟶ (Nat.rec 0 step 1) + 2 -- δ: unfold step -- ⟶ (step 0 (Nat.rec 0 step 0)) + 2 -- ι again -- ⟶ ((Nat.rec 0 step 0) + 2) + 2 -- δ: unfold step -- ⟶ (0 + 2) + 2 ⟶ 4 -- ι on zero, then + example : myDouble 2 = 4 := rfl

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.

1.1.2. Definitional equality and rfl🔗

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 equality a = 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 := rfl example : Nat.succ 0 = 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".

The reduction rules🔗

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 : (fun x => x + 1) 4 = 5 := rfl example : 2 + 2 = 4 := rfl example : List.length [7, 8, 9] = 3 := rfl -- eta: a function equals its eta-expansion example (f : Nat → Nat) : (fun x => f x) = f := rfl -- zeta: a `let` unfolds example : (let x := 4; x + x) = 8 := rfl -- iota: a recursor applied to a constructor example (b : Nat) (s : Nat → Nat → Nat) : Nat.rec (motive := fun _ => Nat) b s 0 = b := rfl example (b : Nat) (s : Nat → Nat → Nat) (n : Nat) : Nat.rec (motive := fun _ => Nat) b s (n + 1) = s n (Nat.rec b s n) := rfl -- delta + iota: a defined function on a literal def twice (n : Nat) : Nat := 2 * n example : twice 3 = 6 := rfl

Conversely, rfl fails 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 mismatch rfl has type ?m.9 = ?m.9 but is expected to have type 0 + 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 = n induction n with ⊢ 0 + 0 = 0 All 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.

1.1.3. Bool🔗

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):

🔗inductive type
Bool : Type
Bool : Type

The Boolean values, true and false.

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.

Bool.false : Bool

The Boolean value false, not to be confused with the proposition False.

Bool.true : Bool

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 : (bif true then "Hi" else "Salut") = "Hi" := rfl -- and in general `bif b then f else e` is `Bool.rec e f b`: example {α : Type} (e f : α) : (bif false then f else e) = Bool.rec e f false := 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) : (bif b then "Hi" else "Salut") = Bool.rec "Salut" "Hi" b := b:Bool⊢ (bif b then "Hi" else "Salut") = Bool.rec "Salut" "Hi" b Tactic `rfl` failed: The left-hand side bif b then "Hi" else "Salut" is not definitionally equal to the right-hand side Bool.rec "Salut" "Hi" b b:Bool⊢ (bif b then "Hi" else "Salut") = Bool.rec "Salut" "Hi" bb:Bool⊢ (bif b then "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):

example (b : Bool) : (bif b then "Hi" else "Salut") = Bool.rec "Salut" "Hi" b := b:Bool⊢ (bif b then "Hi" else "Salut") = Bool.rec "Salut" "Hi" b ⊢ (bif false then "Hi" else "Salut") = Bool.rec "Salut" "Hi" false⊢ (bif true then "Hi" else "Salut") = Bool.rec "Salut" "Hi" true ⊢ (bif false then "Hi" else "Salut") = Bool.rec "Salut" "Hi" false⊢ (bif true then "Hi" else "Salut") = Bool.rec "Salut" "Hi" true All goals completed! 🐙

Note that Bool also carries the usual &&, ||, !.

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.

def myNot : Bool → Bool | false => true | true => false example : myNot false = true := rfl

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)

1.1.4. The propositions True and False🔗

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):

🔗inductive proposition
True : Prop
True : Prop

True is a proposition and has only an introduction rule, True.intro : True. In other words, True is simply true, and has a canonical proof, True.intro For more information: Propositional Logic

True.intro : True

True is true, and True.intro (or more commonly, trivial) is the proof.

So proving True is as easy as naming that constructor:

example : True := True.intro example : True := trivial example : True := ⊢ True All goals completed! 🐙

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:

🔗inductive proposition
False : Prop
False : Prop

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

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):

False.rec : (motive : False → Sort u) → (t : False) → motive t
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
example (h : False) : 0 = 1 := False.elim h example (h : False) (P : Prop) : P := h.elim

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.

1.2. Functions, inductive types, structures🔗

Here are the slides for this chapter.

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):

def aBool : Bool := false def answer : ℕ := 42 def square : ℕ → ℕ := fun n => n * n def zeroNeOne : Prop := 0 ≠ 1

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 n def ltSucc : Prop := ∀ n : ℕ, n < n + 1 -- the type of vectors in ℝⁿ depends on n def RVec (n : ℕ) : Type := Fin n → ℝ def zeroVec (n : ℕ) : RVec n := 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.

1.2.1. Commands for terms🔗

Six commands recur in every chapter.

Three of them make a term known:

  • 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.

def four : ℕ := 2 + 2 theorem four_eq : four = 4 := rfl example : four = 4 := rfl four : ℕ#check four -- four : ℕ 4#eval four -- 4 def four : ℕ := 2 + 2#print four -- def four : ℕ := 2 + 2

The text after -- is a comment; in the examples it shows what Lean prints.

Why Lean keeps theorem apart from def is explained in Why Prop is special.

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:

theorem swap_of_and (P Q : Prop) (h : P ∧ Q) : Q ∧ P := P:PropQ:Proph:P ∧ Q⊢ Q ∧ P P:PropQ:Proph:P ∧ Q⊢ QP:PropQ:Proph:P ∧ Q⊢ P P:PropQ:Proph:P ∧ Q⊢ Q All goals completed! 🐙 P:PropQ:Proph:P ∧ Q⊢ P All goals completed! 🐙 theorem swap_of_and : ∀ (P Q : Prop), P ∧ Q → Q ∧ P := fun P Q h => ⟨h.right, h.left⟩#print swap_of_and -- theorem swap_of_and : ∀ (P Q : Prop), P ∧ Q → Q ∧ P := -- fun P Q h => ⟨h.right, h.left⟩

1.2.2. The universe hierarchy🔗

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 (Type 0 : Type 1) -- `Type 0` is `Type` Type 1 : Type 2#check (Type 1 : Type 2) -- Type 1 : Type 2

The whole tower is captured by a single keyword Sort:

  • Sort 0 is Prop;

  • Sort 1 is Type 0, i.e. Type;

  • Sort (u+1) is Type u.

example : Sort 0 = Prop := rfl example : Sort 1 = Type := rfl example : Type = Type 0 := rfl

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.

1.2.3. Function types and Π-types🔗

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.

fun n => n + 1 : ℕ → ℕ#check (fun n => n + 1 : ℕ → ℕ) 5#eval (fun n : ℕ => n + 1) 4 -- 5 example : (fun n : ℕ => n + 1) 4 = 5 := rfl

Defining functions🔗

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:

def double (n : ℕ) : ℕ := 2 * n 10#eval double 5 -- 10 example : double = fun n => 2 * n := rfl

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.

def add (a b : ℕ) : ℕ := a + b 7#eval add 3 4 -- 7 add 3 : ℕ → ℕ#check add 3 -- add 3 : ℕ → ℕ

The type of add is ℕ → ℕ → ℕ, which reads as ℕ → (ℕ → ℕ); so add 3 is itself a function of type ℕ → ℕ.

Anonymous functions🔗

A function built with fun needs no name; it can be applied on the spot:

fun x => x + 1 : ℕ → ℕ#check (fun x : ℕ ↦ x + 1) -- fun x => x + 1 : ℕ → ℕ 6#eval (fun x : ℕ ↦ x + 1) 5 -- 6 fun x y => x * y : ℕ → ℕ → ℕ#check (fun x y : ℕ ↦ x * y) -- fun x y => x * y : ℕ → ℕ → ℕ 12#eval (fun x y : ℕ ↦ x * y) 3 4 -- 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.

Dependent functions🔗

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:

example : ∀ n : ℕ, n < n + 1 := fun n => Nat.lt_succ_self n example : ((n : ℕ) → n < n + 1) = (∀ n : ℕ, n < n + 1) := rfl

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:

def sevenMod : (n : ℕ) → ZMod n := fun _ => 7 sevenMod 5 : ZMod 5#check sevenMod 5 -- sevenMod 5 : ZMod 5 2#eval sevenMod 5 -- 2 7#eval sevenMod 0 -- 7

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.

Polymorphic functions🔗

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 α:

def myId (α : Type) (a : α) : α := a myId ℕ 42 : ℕ#check myId ℕ 42 -- myId ℕ 42 : ℕ myId String "hi" : String#check myId String "hi" -- myId String "hi" : String

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:

def myId' {α : Type} (a : α) : α := a myId' 42 : ℕ#check myId' 42 -- myId' 42 : ℕ @myId' : {α : Type} → α → α#check @myId' -- {α : Type} → α → α

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:

universe u def idOne (α : Type u) (a : α) : α := a def idStar {α : Type*} (a : α) : α := a

This is why signatures throughout Mathlib read {α : Type*}: the same definition then applies whether α is small like ℕ or large like Type itself.

Lean's own identity function is defined in its Prelude as

def id {α : Sort u} (a : α) : α := a

With Sort u instead of Type u it covers Prop as well, so id h : P for a proof h : P:

id rfl : 1 = 1#check id (rfl : 1 = 1) -- id rfl : 1 = 1

Proofs as arguments🔗

An argument may also be a proof. A division that demands a proof that the denominator is not zero cannot be called with zero:

def safeDiv (a b : ℤ) (_ : b ≠ 0) : ℤ := a / b 3#eval safeDiv 10 3 (⊢ 3 ≠ 0 All goals completed! 🐙) -- 3

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.

1.2.4. Inductive types🔗

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:

inductive MyNat where | zero : MyNat | succ (n : MyNat) : MyNat

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 recursor MyNat.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.

MyNat.zero.succ : MyNat#check (MyNat.succ MyNat.zero : MyNat) example : MyNat := .succ (.succ .zero)

Inductive types also cover non-recursive data:

inductive Colour where | red | green | blue example : Colour := .green

and types with a parameter:

-- `MyOption α` is `none` or `some a` with `a : α` inductive MyOption (α : Type) where | none : MyOption α | some (a : α) : MyOption α example : MyOption ℕ := .some 3

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:

def MyENat : 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:

example : ℕ∞ = MyENat := rfl example : (⊤ : ℕ∞) = Option.none := rfl example : (3 : ℕ∞) = Option.some 3 := rfl

The extended non-negative reals ℝ≥0∞, the values of a measure in Measure theory, are built the same way, as WithTop ℝ≥0.

Disjunction is an inductive type with two constructors: a proof of P ∨ Q is a proof of P or a proof of Q, marked by the constructor. Declared by hand:

inductive MyOr (a b : Prop) : Prop where | inl : a → MyOr a b | inr : b → MyOr a b example (P Q : Prop) (hP : P) : MyOr P Q := .inl hP

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.

1.2.5. Structures🔗

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:

structure Point where x : ℕ 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.

Point.mk : ℕ → ℕ → Point#check (Point.mk : ℕ → ℕ → Point) Point.x : Point → ℕ#check (Point.x : Point → ℕ) example : (Point.mk 3 4).x = 3 := rfl

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.

example (p : Point) : p = Point.mk p.x p.y := rfl

Building structure values🔗

Besides Point.mk, Lean has three more ways to call the constructor:

def origin : Point := { x := 0, y := 0 } def p1 : Point := ⟨1, 2⟩ def p2 : Point := Point.mk 3 4 def p3 : Point where x := 0 y := 0

They are the record form { x := …, y := … }, the anonymous constructor ⟨...⟩ (typed \< and \>), the explicit Point.mk, and the block where 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:

{ x := 0, y := 0 } : Point#check ({ x := 0, y := 0 } : Point) 1#eval p1.x -- 1 2#eval p1.y -- 2

A new value can be built from an existing one, changing only some fields, with the with keyword:

def p4 : Point := { p1 with y := 10 } -- p4.x = 1, p4.y = 10

Structures are immutable, so this creates a new Point rather than modifying p1.

Defaults and extensions🔗

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, ... structure ArithProg where start : ℕ := 0 step : ℕ := 1 def evens : ArithProg := { step := 2 } 0#eval evens.start -- 0 (the default) 2#eval evens.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:

structure Point3D extends Point where z : ℕ def q : Point3D := { x := 1, y := 2, z := 3 } 1#eval q.x -- 1 (inherited from Point) 3#eval q.z -- 3

Mathlib builds its algebraic structures in this way: a commutative ring extends a ring, which extends a semiring.

Operations🔗

Operations on a structure are ordinary functions. If their name begins with the name of the type, they can be called with a dot, as projections are:

def Point.normSq (p : Point) : ℕ := p.x * p.x + p.y * p.y 25#eval p2.normSq -- 25

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:

structure MyComplex where re : ℤ im : ℤ def MyComplex.add (a b : MyComplex) : MyComplex := { re := a.re + b.re, im := a.im + b.im } def MyComplex.mul (a b : MyComplex) : MyComplex := { re := a.re * b.re - a.im * b.im, im := a.re * b.im + a.im * b.re } def i : MyComplex := { re := 0, im := 1 } -1#eval (MyComplex.mul i i).re -- -1

Data with a property🔗

A field may be a proof. Then a structure bundles data together with a property, here a map ℤ → ℤ together with a proof that it respects addition:

structure IntAddMap where toFun : ℤ → ℤ map_add : ∀ x y, toFun (x + y) = toFun x + toFun y def triple : IntAddMap where toFun x := 3 * x map_add x y := mul_add 3 x y 12#eval triple.toFun 4 -- 12

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 → Fin n#check @Fin.mk -- {n : ℕ} → (val : ℕ) → val < n → Fin n example : Fin 3 := ⟨2, ⊢ 2 < 3 All goals completed! 🐙⟩ example (n : ℕ) (h : 0 < n) : Fin n := ⟨0, h⟩ 2#eval (⟨2, ⊢ 2 < 3 All goals completed! 🐙⟩ : Fin 3).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.last : (n : ℕ) → Fin (n + 1)#check @Fin.last -- (n : ℕ) → Fin (n + 1) example (a b : Fin 3) (h : a.val = b.val) : a = b := Fin.ext h

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):

example {n : ℕ} (a b : Fin n) (h : a.val = b.val) : a = b := n:ℕa:Fin nb:Fin nh:↑a = ↑b⊢ a = b n:ℕb:Fin nval✝:ℕisLt✝:val✝ < nh:↑⟨val✝, isLt✝⟩ = ↑b⊢ ⟨val✝, isLt✝⟩ = b; n:ℕval✝¹:ℕisLt✝¹:val✝ < nval✝:ℕisLt✝:val✝ < nh:↑⟨val✝¹, isLt✝¹⟩ = ↑⟨val✝, isLt✝⟩⊢ ⟨val✝¹, isLt✝¹⟩ = ⟨val✝, isLt✝⟩; n:ℕval✝:ℕisLt✝¹:val✝ < nisLt✝:val✝ < n⊢ ⟨val✝, isLt✝¹⟩ = ⟨val✝, isLt✝⟩; All goals completed! 🐙

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.

Conjunction🔗

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.

example (P Q : Prop) (hP : P) (hQ : Q) : P ∧ Q := ⟨hP, hQ⟩ example (P Q : Prop) (h : P ∧ Q) : Q ∧ P := ⟨h.2, h.1⟩

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.

Structures and inductive types🔗

The basic types of Lean are all inductive types, most of them twice: once in Type for data, once in Prop for propositions.

constructors

data (Type)

proposition (Prop)

none

Empty

False

one, without arguments

Unit

True

two, without arguments

Bool

—

one, with two arguments (a structure)

α × β

P ∧ Q

two, with one argument each

α ⊕ β

P ∨ Q

one, with a value and a proof

{x : α // P x}

∃ x, P x

recursive

ℕ, List α

n ≤ m on ℕ

∃, subtypes and ≤ are the subject of chapter 1.4.

1.3. Pattern matching and recursion🔗

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.

1.3.1. Pattern matching🔗

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:

def factorial : ℕ → ℕ | 0 => 1 | n + 1 => (n + 1) * factorial n

Each branch may use the variables introduced by its pattern (here n on the right-hand side). Lean checks two things automatically:

  1. Exhaustiveness. Every constructor of ℕ is covered (the cases 0 and n + 1 exhaust ℕ). If you forget a case, Lean complains.

  2. 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:

def MyNat.double : MyNat → MyNat | .zero => .zero | .succ n => .succ (.succ (MyNat.double n)) def MyNat.toNat : MyNat → ℕ | .zero => 0 | .succ n => MyNat.toNat n + 1 2#eval (MyNat.double (.succ .zero)).toNat -- 2

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 default def Option.getD' {α : Type*} (d : α) : Option α → α | none => d | some a => a -- A recursive function on List α def length' {α : Type*} : List α → ℕ | [] => 0 | _ :: xs => 1 + length' xs

The same syntax can be used inside a term with match:

def isEmpty' {α : Type*} (l : List α) : Bool := match l with | [] => true | _ :: _ => false

1.3.2. Structural recursion🔗

The definitions above are recursive: they call themselves. A classic example with two base cases is the Fibonacci sequence:

def fib : ℕ → ℕ | 0 => 0 | 1 => 1 | n + 2 => fib n + fib (n + 1) 55#eval fib 10 -- 55

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:

-- fib 3 ⟶ fib 1 + fib 2 ⟶ 1 + (fib 0 + fib 1) ⟶ 1 + (0 + 1) example : fib 3 = 2 := rfl

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:

def fail to show termination for loop with errors failed to infer structural recursion: Not considering parameter n of loop: it is unchanged in the recursive calls no parameters suitable for structural recursion well-founded recursion cannot be used, `loop` does not take any (non-fixed) argumentsloop (n : ℕ) : ℕ := loop n + 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.

def fibPair (n : ℕ) : ℕ × ℕ := Nat.rec (0, 1) (fun _ p => (p.2, p.1 + p.2)) n example : fibPair 10 = (55, 89) := rfl

Lean's own translation of fib carries the values at all smaller arguments (Course-of-values recursion).

1.3.3. The recursor🔗

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 motive T → 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.

Top: inductive MyNat where | zero : MyNat | succ (n : MyNat) : MyNat. Bottom: MyNat.rec with the implicit motive : MyNat → Sort u, then (zero : motive MyNat.zero), then (succ : (n : MyNat) → motive n → motive (MyNat.succ n)), then (t : MyNat) → motive t. Arrows: the type MyNat gives the motive; the constructor zero gives the case zero; the constructor succ gives the case succ; its recursive argument n gives (n : MyNat) → motive n.

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:

  1. The parameters of T, such as α in MyOption α, as implicit arguments.

  2. The motive motive : T → Sort u, the type of the result, which may depend on the term.

  3. 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ₖ).

  4. 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.

Top: inductive T where | c₁ (b₁ : B₁) … (bₗ : Bₗ) (r₁ … rₖ : T) : T | …. Bottom: T.rec with the implicit motive : T → Sort u, then the case f₁ : (b₁ : B₁) → … → (bₗ : Bₗ) → (r₁ … rₖ : T) → motive r₁ → … → motive rₖ → motive (c₁ b₁ … bₗ r₁ … rₖ), then the other cases and (t : T) → motive t. Arrows: the type gives the motive; the constructor c₁ gives the case f₁; its non-recursive arguments are passed on; its recursive arguments also give the values motive rⱼ; the other constructors give the other cases.

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ₘ:

R (c₁ b₁ … bₗ r₁ … rₖ)  ⟶  f₁ b₁ … bₗ r₁ … rₖ (R r₁) … (R rₖ)

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:

recursor MyNat.rec.{u} : {motive : MyNat → Sort u} → motive MyNat.zero → ((n : MyNat) → motive n → motive n.succ) → (t : MyNat) → motive t number of parameters: 0 number of indices: 0 number of motives: 1 number of minors: 2 rules: for MyNat.zero (0 fields): fun motive zero succ => zero for MyNat.succ (1 fields): fun motive zero succ n => succ n (MyNat.rec zero succ n)#print MyNat.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.

Examples🔗

@List.rec : {α : Type u_2} → {motive : List α → Sort u_1} → motive [] → ((head : α) → (tail : List α) → motive tail → motive (head :: tail)) → (t : List α) → motive t#check @List.rec -- {α : Type v} → {motive : List α → Sort u} → -- motive [] → -- ((head : α) → (tail : List α) → -- motive tail → motive (head :: tail)) → -- (t : List α) → motive t @Colour.rec : {motive : Colour → Sort u_1} → motive Colour.red → motive Colour.green → motive Colour.blue → (t : Colour) → motive t#check @Colour.rec -- {motive : Colour → Sort u} → -- motive .red → motive .green → motive .blue → -- (t : Colour) → motive t @MyOption.rec : {α : Type} → {motive : MyOption α → Sort u_1} → motive MyOption.none → ((a : α) → motive (MyOption.some a)) → (t : MyOption α) → motive t#check @MyOption.rec -- {α : Type} → {motive : MyOption α → Sort u} → -- motive .none → -- ((a : α) → motive (.some a)) → -- (t : MyOption α) → motive t @Point.rec : {motive : Point → Sort u_1} → ((x y : ℕ) → motive { x := x, y := y }) → (t : Point) → motive t#check @Point.rec -- {motive : Point → Sort u} → -- ((x y : ℕ) → motive { x := x, y := y }) → -- (t : Point) → motive t

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).

Case splits: casesOn🔗

Besides T.rec, Lean defines T.casesOn, the recursor without the values at the recursive arguments. It takes t before the cases:

Top: the declaration of MyNat. Bottom: MyNat.casesOn with the implicit motive : MyNat → Sort u, then (t : MyNat), then (zero : motive MyNat.zero), then (succ : (n : MyNat) → motive (MyNat.succ n)), then motive t. Arrows as for MyNat.rec; the recursive argument n gives only (n : MyNat).

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:

@Nat.casesOn : {motive : ℕ → Sort u_1} → (t : ℕ) → motive Nat.zero → ((n : ℕ) → motive n.succ) → motive t#check @Nat.casesOn -- {motive : ℕ → Sort u} → (t : ℕ) → -- motive Nat.zero → -- ((n : ℕ) → motive (Nat.succ n)) → motive t

Are all cases covered?🔗

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] def fib.match_1.{u_1} : (motive : ℕ → Sort u_1) → (x : ℕ) → (Unit → motive 0) → (Unit → motive 1) → ((n : ℕ) → motive n.succ.succ) → motive x := fun motive x h_1 h_2 h_3 => Nat.casesOn x (h_1 ()) fun n => Nat.casesOn n (h_2 ()) fun n => h_3 n#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:

def fib' : ℕ → ℕ Missing cases: (Nat.succ Nat.zero)| 0 => 0 | n + 2 => fib' n + fib' (n + 1)

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").

1.3.4. Recursion on trees🔗

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:

inductive BinTree where | leaf : BinTree | node (l : BinTree) (a : ℕ) (r : BinTree) : BinTree

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 subtree l and right subtree r. 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 trees. First: a single square, the term .leaf, height 0. Second: a circle 4 with two squares below it, the term .node .leaf 4 .leaf, height 1. Third: a circle 3 with a square on the left and the circle 4 on the right, which again has two squares below it; the term .node .leaf 3 (.node .leaf 4 .leaf), height 2.

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:

def BinTree.height : BinTree → ℕ | .leaf => 0 | .node l _ r => max l.height r.height + 1 example : BinTree.leaf.height = 0 := rfl example : (BinTree.node .leaf 4 .leaf).height = 1 := rfl example : (BinTree.node .leaf 3 (.node .leaf 4 .leaf)).height = 2 := rfl

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} → motive BinTree.leaf → ((l : BinTree) → (a : ℕ) → (r : BinTree) → motive l → motive r → motive (l.node a r)) → (t : BinTree) → motive t#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:

noncomputable def BinTree.sum : BinTree → ℕ := BinTree.rec 0 (fun _ a _ sl sr => sl + a + sr) example : (BinTree.node .leaf 3 (.node .leaf 4 .leaf)).sum = 7 := rfl

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.

1.3.5. Termination by a measure🔗

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.

def log2 (n : Nat) : Nat := if 2 ≤ n then 1 + log2 (n / 2) else 0 4#eval log2 16 -- 4

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:

def fail to show termination for log2' with errors failed to infer structural recursion: Cannot use parameter n: failed to eliminate recursive application log2' (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 goal n:ℕ⊢ 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.

Grid of the points (m, n) with m + n at most 4, each labelled with its position in Cantor's enumeration: 0 at (0, 0); 1, 2 on the next diagonal; 3, 4, 5; 6 to 9; 10 to 14. Arrows run down each diagonal from (0, n) to (n, 0)

Cantor's enumeration of ℕ × ℕ. The point (m, n) carries pairIndex m n; the arrows run along a diagonal.

In Lean, read backwards from (m, n):

def pairIndex : ℕ → ℕ → ℕ | 0, 0 => 0 | 0, n + 1 => pairIndex n 0 + 1 | m + 1, n => pairIndex m (n + 1) + 1 termination_by m n => (m + n, m) decreasing_by all_goals (m:ℕn:ℕ⊢ (m + (n + 1), m).1 < (m.succ + n, m.succ).1 ∨ (m + (n + 1), m).1 = (m.succ + n, m.succ).1 ∧ (m + (n + 1), m).2 < (m.succ + n, m.succ).2; All goals completed! 🐙) 8#eval pairIndex 2 1 -- 8

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#synth WellFoundedRelation (ℕ × ℕ) -- 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:

def logb (b n : ℕ) : ℕ := if h : 2 ≤ b ∧ b ≤ n then 1 + logb b (n / b) else 0 termination_by n decreasing_by exact Nat.div_lt_self (b:ℕn:ℕh:2 ≤ b ∧ b ≤ n⊢ 0 < n All goals completed! 🐙) h.1 3#eval logb 10 1000 -- 3

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:

example : fib 10 = 55 := rfl example (n : ℕ) : fib (n + 2) = fib n + fib (n + 1) := rfl

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 : log2 16 = 4 := Type mismatch rfl has type ?m.7 = ?m.7 but is expected to have type log2 16 = 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 : ℕ) : log2 n = if 2 ≤ n then 1 + log2 (n / 2) else 0#check log2.eq_1 -- log2.eq_1 (n : ℕ) : log2 n = -- if 2 ≤ n then 1 + log2 (n / 2) else 0 example : log2 16 = 4 := ⊢ log2 16 = 4 All goals completed! 🐙 example (n : ℕ) (h : 2 ≤ n) : log2 n = 1 + log2 (n / 2) := n:ℕh:2 ≤ n⊢ log2 n = 1 + log2 (n / 2) n:ℕh:2 ≤ n⊢ (if 2 ≤ n then 1 + log2 (n / 2) else 0) = 1 + log2 (n / 2) All goals completed! 🐙

Proofs by induction that follow the recursion of a function, one case per branch, are done with fun_induction (induction).

1.3.7. Course-of-values recursion🔗

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:

theorem fib_pos : (n : ℕ) → 0 < fib (n + 1) ⊢ 0 < fib (0 + 1) ⊢ 0 < fib (0 + 1) All goals completed! 🐙 ⊢ 0 < fib (1 + 1) ⊢ 0 < fib (1 + 1) All goals completed! 🐙 n:ℕ⊢ 0 < fib (n + 2 + 1) n:ℕ⊢ 0 < fib (n + 2 + 1) n:ℕh:0 < fib (n + 1)⊢ 0 < fib (n + 2 + 1) n:ℕh:0 < fib (n + 1)⊢ 0 < fib (n + 1) + fib (n + 2) All goals completed! 🐙

The case n + 2 uses the statement for n, two steps back. With the induction tactic the hypothesis is only the statement one step back.

1.3.8. Strict positivity🔗

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:

inductive MyTree where | leaf (a : ℕ) : MyTree | node (f : ℕ → MyTree) : MyTree

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.

example : MyTree := .leaf 7 example : MyTree := .node (fun n => .leaf n) example : MyTree := .node (fun n => if n = 0 then .node .leaf else .leaf n)

A root node with edges labelled 0, 1, 2, 3 and dots. Edge 0 leads to a node whose edges 0, 1, 2, 3 lead to the leaves 0, 1, 2, 3; edges 1, 2, 3 lead to the leaves 1, 2, 3.

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.

def MyTree.leftmost : MyTree → ℕ | .leaf a => a | .node f => (f 0).leftmost def MyTree.chain : ℕ → MyTree | 0 => .leaf 0 | n + 1 => .node (fun _ => MyTree.chain n) def MyTree.unbounded : MyTree := .node MyTree.chain

The leaf case is what gets the type off the ground. Positivity constrains only where MyTree 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:

example (Bad : Type) (mk : (Bad → False) → Bad) (unmk : Bad → (Bad → False)) : False := let neg : Bad → False := fun b => unmk b b neg (mk neg)

Strict positivity outlaws exactly the negative occurrence that ties this self-applying knot, the same concern that rules out Type : Type.

Why positivity is enough🔗

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.

1.4. Pairs, subtypes, families, quotients🔗

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.

1.4.1. Pairs and Σ-types🔗

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:

structure Sigma.{u, v} {α : Type u} (β : α → Type v) : Type (max u v) number of parameters: 2 fields: Sigma.fst : α Sigma.snd : β self.fst constructor: Sigma.mk.{u, v} {α : Type u} {β : α → Type v} (fst : α) (snd : β fst) : Sigma β#print Sigma def aPair : (n : ℕ) × Fin (n + 1) := ⟨3, Fin.last 3⟩ 3#eval aPair.1 -- 3 aPair.snd : Fin (aPair.fst + 1)#check aPair.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:

-- Σ: 1 + 2 + 3 + 4 = 10 elements example : Fintype.card ((n : Fin 4) × Fin (n + 1)) = 10 := ⊢ Fintype.card ((n : Fin 4) × Fin (↑n + 1)) = 10 All goals completed! 🐙 -- Π: 1 · 2 · 3 · 4 = 24 elements example : Fintype.card ((n : Fin 4) → Fin (n + 1)) = 24 := ⊢ Fintype.card ((n : Fin 4) → Fin (↑n + 1)) = 24 All goals completed! 🐙

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.

1.4.2. Subtypes🔗

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 (a b : {n : ℕ // 0 < n}) (h : a.val = b.val) : a = b := Subtype.ext h -- The type of natural numbers greater than 5 def BigNat : Type := {n : ℕ // n > 5} def seven : BigNat := ⟨7, ⊢ 7 > 5 All goals completed! 🐙⟩ 7#eval seven.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 set s : 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.

1.4.3. Type families🔗

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 Bool def BoolFamily : Bool → Type | true => ℕ | false => String -- Dependent function using the type family def boolFamilyExample : (b : Bool) → BoolFamily b | 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 family def fiber (f : ℕ → ℕ) (b : ℕ) : Type := {a : ℕ // f a = b} -- An element of the fiber of (· * 2) over 10 def fiberExample : 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 3 def myVec : Fin 3 → ℕ := ![10, 20, 30] 10#eval myVec 0 -- 10 20#eval myVec 1 -- 20 30#eval myVec 2 -- 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 numbers def myMatrix : Fin 2 → Fin 3 → ℕ := ![![1, 2, 3], ![4, 5, 6]] 2#eval myMatrix 0 1 -- 2 6#eval myMatrix 1 2 -- 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.

1.4.4. Indexed families and inductive predicates🔗

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:

inductive Vec (α : Type) : ℕ → Type where | nil : Vec α 0 | cons {n : ℕ} (a : α) (v : Vec α n) : Vec α (n + 1)

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:

def Vec.head {α : Type} {n : ℕ} : Vec α (n + 1) → α | .cons a _ => a 1#eval (Vec.cons 1 (Vec.cons 2 .nil)).head -- 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:

inductive MyEven : ℕ → Prop where | zero : MyEven 0 | add_two (n : ℕ) : MyEven n → MyEven (n + 2) example : MyEven 4 := .add_two 2 (.add_two 0 .zero)

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:

example : ¬ MyEven 1 := ⊢ ¬MyEven 1 h:MyEven 1⊢ False All goals completed! 🐙 example (n : ℕ) (h : MyEven (n + 2)) : MyEven n := n:ℕh:MyEven (n + 2)⊢ MyEven n cases h with n:ℕh':MyEven n⊢ MyEven n All goals completed! 🐙

Mathlib defines Even n differently, as ∃ r, n = r + r. But ≤ on ℕ and equality itself are inductive predicates of exactly this kind:

protected inductive Nat.le : ℕ → ℕ → Prop number of parameters: 1 constructors: Nat.le.refl : ∀ {n : ℕ}, n.le n Nat.le.step : ∀ {n m : ℕ}, n.le m → n.le m.succ#print Nat.le inductive Eq.{u_1} : {α : Sort u_1} → α → α → Prop number of parameters: 2 constructors: Eq.refl : ∀ {α : Sort u_1} (a : α), a = a#print Eq

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.

1.4.5. Propositions as types🔗

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).

Implication, negation, and ∀🔗

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):

example (P Q : Prop) (hP : P) (hPQ : P → Q) : Q := hPQ hP example (P Q R : Prop) : (P → Q) → (Q → R) → (P → R) := fun hPQ hQR hP => hQR (hPQ hP)

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.

example (P : Prop) : (¬P) = (P → False) := rfl example (P : Prop) (hP : P) (hnP : ¬P) : False := hnP hP

True and 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:

example : True := True.intro example (C : Prop) (h : False) : C := nomatch h example (C : Prop) (h : False) : C := h.elim

Conjunction🔗

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.

Disjunction🔗

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.

example (P Q R : Prop) (h : P ∨ Q) (hPR : P → R) (hQR : Q → R) : R := match h with | Or.inl hP => hPR hP | Or.inr hQ => hQR hQ example (P Q R : Prop) (h : P ∨ Q) (hPR : P → R) (hQR : Q → R) : R := h.elim hPR hQR

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.

The existential quantifier🔗

∃ x, P x is notation for Exists P, an inductive type with one constructor that takes a witness and a proof:

inductive Exists.{u} : {α : Sort u} → (α → Prop) → Prop number of parameters: 2 constructors: Exists.intro : ∀ {α : Sort u} {p : α → Prop} (w : α), p w → Exists p#print Exists

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.

example : ∃ n : ℕ, n > 5 := ⟨7, ⊢ 7 > 5 All goals completed! 🐙⟩ example (P Q : ℕ → Prop) (h : ∃ n, P n ∧ Q n) : ∃ n, Q n := match h with | ⟨n, hn⟩ => ⟨n, hn.2⟩

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.

def bigSeven : {n : ℕ // n > 5} := ⟨7, ⊢ 7 > 5 All goals completed! 🐙⟩ 7#eval bigSeven.val -- 7

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 some P x holds. In the same way \prod_x |P(x)| is positive exactly if every P 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 dictionary🔗

proposition

type former

a proof is

P → Q

function type

a function from proofs of P to proofs of Q

∀ x : α, P x

Π-type

a function taking each x to a proof of P x

P ∧ Q

structure, like α × β

a pair ⟨hP, hQ⟩

P ∨ Q

inductive, like a disjoint union

Or.inl hP or Or.inr hQ

∃ x : α, P x

inductive, like a Σ-type

a pair ⟨a, h⟩ with h : P a

True

inductive, one constructor

True.intro

False

inductive, no constructor

there is none

¬P

P → False

a function from proofs of P to False

A statement is a term of type Prop whether or not anyone has a proof. Goldbach's conjecture, with Even and Nat.Prime from Mathlib:

theorem declaration uses `sorry`goldbach : ∀ n : ℕ, n > 2 → Even n → ∃ p q : ℕ, Nat.Prime p ∧ Nat.Prime q ∧ n = p + q := ⊢ ∀ n > 2, Even n → ∃ p q, Nat.Prime p ∧ Nat.Prime q ∧ n = p + q All goals completed! 🐙

A term that replaces the sorry is a proof of the conjecture.

1.4.6. Quotient types🔗

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) → α → Quot r#check @Quot.mk -- (r : α → α → Prop) → α → Quot r @Quot.lift : {α : Sort u_1} → {r : α → α → Prop} → {β : Sort u_2} → (f : α → β) → (∀ (a b : α), r a b → f a = f b) → Quot r → β#check @Quot.lift -- (f : α → β) → (∀ a b, r a b → f a = f b) → -- Quot r → β @Quot.ind : ∀ {α : Sort u_1} {r : α → α → Prop} {β : Quot r → Prop}, (∀ (a : α), β (Quot.mk r a)) → ∀ (q : Quot r), β q#check @Quot.ind example (r : Nat → Nat → Prop) (f : Nat → Nat) (h : ∀ a b, r a b → f a = f b) (a : Nat) : Quot.lift f h (Quot.mk r a) = f a := rfl

One axiom🔗

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} {a b : α}, r a b → Quot.mk r a = Quot.mk r b#check @Quot.sound -- r a b → Quot.mk r a = Quot.mk r b 'Quot.sound' depends on axioms: [Quot.sound]#print axioms Quot.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.

Function extensionality from Quot.sound🔗

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.

theorem myFunext {α β : Type*} {f g : α → β} (h : ∀ x, f x = g x) : f = g := α:Type u_1β:Type u_2f:α → βg:α → βh:∀ (x : α), f x = g x⊢ f = g α:Type u_1β:Type u_2f:α → βg:α → βh:∀ (x : α), f x = g xeqv:(α → β) → (α → β) → Prop := fun f g => ∀ (x : α), f x = g x⊢ f = g α:Type u_1β:Type u_2f:α → βg:α → βh:∀ (x : α), f x = g xeqv:(α → β) → (α → β) → Prop := fun f g => ∀ (x : α), f x = g xhq:Quot.mk eqv f = Quot.mk eqv g⊢ f = g α:Type u_1β:Type u_2f:α → βg:α → βh:∀ (x : α), f x = g xeqv:(α → β) → (α → β) → Prop := fun f g => ∀ (x : α), f x = g xhq:Quot.mk eqv f = Quot.mk eqv ghf:f = fun x => Quot.lift (fun f => f x) ⋯ (Quot.mk eqv f)⊢ f = g α:Type u_1β:Type u_2f:α → βg:α → βh:∀ (x : α), f x = g xeqv:(α → β) → (α → β) → Prop := fun f g => ∀ (x : α), f x = g xhq:Quot.mk eqv f = Quot.mk eqv ghf:f = fun x => Quot.lift (fun f => f x) ⋯ (Quot.mk eqv f)hg:g = fun x => Quot.lift (fun g => g x) ⋯ (Quot.mk eqv g)⊢ f = g All goals completed! 🐙 'myFunext' depends on axioms: [Quot.sound]#print axioms myFunext -- [Quot.sound]

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.

Example: the integers mod 2🔗

ℤ/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 2 def SameParity (a b : ℤ) : Prop := a % 2 = b % 2 def Parity : Type := Quot SameParity def Parity.mk (a : ℤ) : Parity := Quot.mk SameParity a example : Parity.mk 7 = Parity.mk 1 := Quot.sound rfl

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:

def Parity.rem : Parity → ℤ := Quot.lift (fun a => a % 2) (fun _ _ h => h) example : Parity.rem (Parity.mk 17) = 1 := rfl

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:

def Parity.toZMod : Parity → ZMod 2 := Quot.lift (fun a => (a : ZMod 2)) (fun a b h => (ZMod.intCast_eq_intCast_iff' a b 2).mpr h)

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.

1.4.7. The four steps at a glance🔗

type

formation

construction

use

computation

function

(x : α) → β x

fun x => e

f a

(fun x => e) a ⟶ e[x := a]

inductive

inductive T

constructors

pattern matching, T.rec

a match on a constructor takes its branch

structure

structure S

⟨a, b⟩, { x := a, … }

projections s.x

(S.mk a b).x ⟶ a

Σ-type

(x : α) × β x

⟨a, b⟩

.1, .2

⟨a, b⟩.1 ⟶ a

subtype

{x : α // P x}

⟨a, h⟩

.val, .property

⟨a, h⟩.val ⟶ a

indexed family

inductive T : I → Sort u

constructors, each fixing an index

pattern matching, cases

a match on a constructor takes its branch

quotient

Quot r

Quot.mk r a

Quot.lift f h

Quot.lift f h (Quot.mk r a) ⟶ f a

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.

1.4.8. Some history🔗

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 : ....

1.5. Rules for building types🔗

This section is published right before the chapter is taught.

1.5.1. The rules of Lean's type theory🔗

This section is published right before the chapter is taught.

Judgements and contexts🔗

This section is published right before the chapter is taught.

Universes🔗

This section is published right before the chapter is taught.

Variables🔗

This section is published right before the chapter is taught.

Function types🔗

This section is published right before the chapter is taught.

Abstraction and application🔗

This section is published right before the chapter is taught.

Conversion🔗

This section is published right before the chapter is taught.

Inductive types🔗

This section is published right before the chapter is taught.

Quotients🔗

This section is published right before the chapter is taught.

Axioms🔗

This section is published right before the chapter is taught.

The kernel and the elaborator🔗

This section is published right before the chapter is taught.

1.5.2. How the universe of a type is determined🔗

This section is published right before the chapter is taught.

1.5.3. Why Prop is special🔗

This section is published right before the chapter is taught.

Tactic mode and term mode🔗

This section is published right before the chapter is taught.

1.6. Typeclasses🔗

This section is published right before the chapter is taught.

1.6.1. The problem typeclasses solve🔗

This section is published right before the chapter is taught.

1.6.2. Defining typeclasses🔗

This section is published right before the chapter is taught.

1.6.3. Data classes and Prop classes🔗

This section is published right before the chapter is taught.

1.6.4. Creating instances🔗

This section is published right before the chapter is taught.

1.6.5. Using deriving🔗

This section is published right before the chapter is taught.

1.6.6. The square bracket notation🔗

This section is published right before the chapter is taught.

1.6.7. Inspecting typeclass arguments with @🔗

This section is published right before the chapter is taught.

1.6.8. Defining multiple instances🔗

This section is published right before the chapter is taught.

1.6.9. How instance resolution works🔗

This section is published right before the chapter is taught.

1.6.10. Output parameters🔗

This section is published right before the chapter is taught.

1.6.11. Propositions as instances: Fact🔗

This section is published right before the chapter is taught.

1.6.12. Where numerals come from (OfNat)🔗

This section is published right before the chapter is taught.

1.6.13. The Decidable typeclass🔗

This section is published right before the chapter is taught.

The classical tactic🔗

This section is published right before the chapter is taught.

1.6.14. Classes over type constructors🔗

This section is published right before the chapter is taught.

Functor🔗

This section is published right before the chapter is taught.

Monad🔗

This section is published right before the chapter is taught.

The do-notation🔗

This section is published right before the chapter is taught.

Lists as a monad🔗

This section is published right before the chapter is taught.

The monad laws🔗

This section is published right before the chapter is taught.

1.6.15. Coercions🔗

This section is published right before the chapter is taught.

1.6.16. The algebraic hierarchy in Mathlib🔗

This section is published right before the chapter is taught.

1.6.17. Managing instances🔗

This section is published right before the chapter is taught.

1.6.18. Practical tips🔗

This section is published right before the chapter is taught.

1.7. Notation and abbreviations🔗

This section is published right before the chapter is taught.

1.7.1. Defining new notation🔗

This section is published right before the chapter is taught.

Prefix and postfix operators🔗

This section is published right before the chapter is taught.

Multi-argument notation🔗

This section is published right before the chapter is taught.

Notation with binders🔗

This section is published right before the chapter is taught.

Scoped notation🔗

This section is published right before the chapter is taught.

1.7.2. Two useful shorthands🔗

This section is published right before the chapter is taught.

1.7.3. The abbrev command🔗

This section is published right before the chapter is taught.