In a mathematics course you define the factorial by recursion and prove facts about it by induction, and the two feel like different activities. In Lean they are one activity. A natural number is zero with finitely many succ steps on top. To define a function on it you say what to do at zero, and how to get the value at n + 1 from the value at n. To prove a statement for every n you give a proof at zero, and a way to get the proof at n + 1 from the proof at n. Under propositions as types (Lecture 1), the second is a special case of the first: a proof by induction is a recursive function whose result type is a proposition.

This lecture follows that idea from definitions to proofs. It then covers recursion that is not structural, where Lean asks you why the function terminates, and inductive predicates: properties defined by rules, like “even” or “reachable in some number of steps”, which you can take apart by cases and induction. Everything here is core Lean, with no Mathlib.

Notebook and cheatsheet

Notebook 4: Induction runs these proofs step by step, shows the goals at each stage, and discovers the helper lemma that reversing a list twice needs. Cheatsheet: induction and its goal states, inductive types and their recursors, termination, inductive, structure and match.

Recursion on an inductive type

To the logic, Nat is not a primitive. It is an inductive type, declared by listing its constructors, the only ways to build a value. (The kernel and the compiler add fast arithmetic on numerals, but that does not change what the type is.)

#print Nat

Lean answers that Nat : Type has two constructors, Nat.zero : Nat and Nat.succ : Nat → Nat. Lists are the same kind of thing: [] and x :: xs. A function on an inductive type is written by pattern matching, one line per constructor:

def double : Nat → Nat
  | 0 => 0
  | n + 1 => double n + 2
 
def mySum : List Nat → Nat
  | [] => 0
  | x :: xs => x + mySum xs
 
#eval double 5          -- 10
#eval mySum [1, 2, 3]   -- 6
Definition 4.1 (Structural recursion).

A recursive definition is structural if every recursive call is applied to a field of the constructor being matched: n inside n + 1, xs inside x :: xs. Every value of an inductive type is a finite tree of constructors, and each call removes at least one of them, so a structural definition terminates on every input.

Lean accepts both definitions above by structural recursion (Definition 4.1) without being asked. How does the kernel, which knows nothing about match, check them? Each inductive declaration comes with one function that the kernel does know: the recursor T.rec, defined in Lecture 2. As a reminder, it takes a motive (the result type, as a function of the input), one argument per constructor saying what to return for that constructor, and a value of T. Applied to a constructor, it reduces to the case given for that constructor, and this rule is how the kernel computes with it.

#check @Nat.rec

Lean prints:

@Nat.rec : {motive : Nat → Sort u_1} → motive Nat.zero → ((n : Nat) → motive n → motive n.succ) → (t : Nat) → motive t

Read it as: give a value for zero, and a function that turns the value at n into the value at n.succ, and you get a value at every t. That is primitive recursion. You can define double with the recursor directly and check that it agrees with the version above:

def double' (n : Nat) : Nat :=
  Nat.rec (motive := fun _ => Nat) 0 (fun _ r => r + 2) n
 
#eval double' 5   -- 10
 
example : double' 5 = double 5 := rfl

Nobody writes functions like this, and Lean does not compile double this way either:

#print double

The body is fun x ↦ Nat.brecOn x double._f. Nat.brecOn is a helper defined from Nat.rec that gives each step the values at all smaller arguments, not only at n, which pattern matching needs when a definition looks two steps back. The details do not matter here. What matters is that the kernel checks a structural definition by checking a term built from Nat.rec, so nothing about match needs to be trusted.

Induction is recursion that returns a proof

Choose a motive whose values are propositions, P : Nat → Prop, and the type of Nat.rec becomes a familiar statement.

Theorem 4.1 (Induction on Nat).

For every P : Nat → Prop, the recursor gives a proof of .

This is not an axiom added to Lean. It is the recursor of the inductive declaration, at a motive in Prop. The induction tactic applies it for you. Here is a statement that needs it:

example (n : Nat) : n + 0 = n := rfl
 
theorem my_zero_add (n : Nat) : 0 + n = n := by
  induction n with
  | zero => rfl
  | succ k ih => rw [← Nat.add_assoc, ih]

Why is n + 0 = n true by rfl and 0 + n = n not? Addition on Nat recurses on its second argument: n + 0 = n and n + (m + 1) = (n + m) + 1 are its two defining equations. So n + 0 computes to n, but 0 + n is stuck while n is a variable, and only induction gets past it. The figure shows the goals that induction n produces.

n : Nat ⊢ 0 + n = n induction n case zero ⊢ 0 + 0 = 0 case succ k : Nat ih : 0 + k = k ⊢ 0 + (k + 1) = k + 1 closed by rfl closed by rw [← Nat.add_assoc, ih] the term: one argument per case Nat.rec (motive := fun n ↦ 0 + n = n) (proof of zero) (fun k ih ↦ proof of succ) n

The zero case is 0 + 0 = 0, which holds by computation. The succ case has a new variable k and the induction hypothesis ih : 0 + k = k, and must prove the statement for k + 1. The rewrite regroups 0 + (k + 1) as 0 + k + 1, and ih turns that into k + 1. #print confirms the shape of the term in the figure:

#print my_zero_add

The term is fun n ↦ Nat.recAux (Eq.refl (0 + 0)) (fun k ih ↦ …) n, and Nat.recAux is Nat.rec with its cases written as 0 and n + 1. The induction principle (Theorem 4.1) is exactly what the tactic used.

Generalizing the induction hypothesis

The induction hypothesis is about the same values of the other variables as the goal. That is sometimes too weak. Here is a sum with an accumulator, the way a programmer writes a loop:

def sumAcc : List Nat → Nat → Nat
  | [], acc => acc
  | x :: xs, acc => sumAcc xs (acc + x)

We want sumAcc xs acc = acc + mySum xs. A first attempt fails at the rewrite:

theorem sumAcc_eq_try (xs : List Nat) (acc : Nat) :
    sumAcc xs acc = acc + mySum xs := by
  induction xs with
  | nil => simp only [sumAcc, mySum, Nat.add_zero]
  | cons x xs ih =>
    simp only [sumAcc, mySum]
    rw [ih]

Lean reports that it did not find an occurrence of the pattern sumAcc xs acc in the target sumAcc xs (acc + x) = acc + (x + mySum xs). The hypothesis is ih : sumAcc xs acc = acc + mySum xs, about the accumulator acc, but the recursive call changed the accumulator to acc + x. The fix is to prove the statement for every accumulator at once. induction xs generalizing acc makes the hypothesis ih : ∀ (acc : Nat), sumAcc xs acc = acc + mySum xs, which applies to acc + x:

theorem sumAcc_eq (xs : List Nat) (acc : Nat) :
    sumAcc xs acc = acc + mySum xs := by
  induction xs generalizing acc with
  | nil => simp only [sumAcc, mySum, Nat.add_zero]
  | cons x xs ih =>
    simp only [sumAcc, mySum]
    rw [ih]
    omega

On paper this is “strengthen the induction hypothesis”. In Lean the symptom is always the same: ih mentions a fixed value where the goal has a different one.

Recursion that is not structural

Halving is not structural: n / 2 is not a field of any constructor of n. Lean accepts this definition anyway:

def myLog2 (n : Nat) : Nat :=
  if n ≤ 1 then 0 else 1 + myLog2 (n / 2)
 
#eval myLog2 1000   -- 9
Definition 4.2 (Well-founded recursion).

A recursive definition uses well-founded recursion when it comes with a measure, a function of the arguments into a well-founded order such as < on Nat (one with no infinite descending chain), and a proof that every recursive call happens at arguments of strictly smaller measure.

When structural recursion fails, Lean tries well-founded recursion (Definition 4.2) with each argument as the measure, and tries to prove each call decreases with decreasing_tactic, which runs simp +arith, omega and assumption. For myLog2 it must prove n / 2 < n knowing ¬n ≤ 1, and omega does it. The definition is then compiled with WellFounded.fix, which is itself defined from the recursor of an inductive predicate, Acc. So well-founded recursion, too, ends in a recursor the kernel checks.

Lean does not always succeed. Euclid’s algorithm recurses on n % m:

def myGcd (m n : Nat) : Nat :=
  if m = 0 then n else myGcd (n % m) m

Lean reports fail to show termination. It explains that structural recursion failed on both parameters, then prints a table of what it could prove about m and n at the call, with ? meaning “all proofs failed”, and ends with Please use termination_by to specify a decreasing measure. The call needs n % m < m, which holds because m ≠ 0, but omega handles % only by a numeral. So we name the measure and prove the step ourselves:

def myGcd (m n : Nat) : Nat :=
  if m = 0 then n else myGcd (n % m) m
termination_by m
decreasing_by exact Nat.mod_lt _ (by omega)
 
#eval myGcd 12 18   -- 6
#print myGcd

termination_by m says the measure is m. decreasing_by gives the proof for the call: its goal is n % m < m, with the hypothesis ¬m = 0 from the if in context, and the library lemma Nat.mod_lt needs exactly 0 < m, which omega supplies.

To prove things about myLog2, ordinary induction is the wrong tool: the step goes from n / 2 to n, not from n to n + 1. Strong induction lets the step use the statement for every smaller number. In this version of Lean it is Nat.strongRecOn. A second option, fun_induction, builds an induction principle that follows the function’s own recursion, with one case per branch:

theorem myLog2_le (n : Nat) : myLog2 n ≤ n := by
  induction n using Nat.strongRecOn with
  | ind n ih =>
    unfold myLog2
    split
    · omega
    · have := ih (n / 2) (by omega)
      omega
 
theorem myLog2_le' (n : Nat) : myLog2 n ≤ n := by
  fun_induction myLog2 n with
  | case1 n h => omega
  | case2 n h ih => omega

In the first proof, unfold myLog2 replaces the function by its body and split makes one goal per branch of the if.

When no measure is known: partial

Here is a function nobody can prove terminating, because whether it stops on every input is the Collatz conjecture, an open problem:

def collatz (n : Nat) : Nat :=
  if n ≤ 1 then 0
  else if n % 2 = 0 then 1 + collatz (n / 2)
  else 1 + collatz (3 * n + 1)

The error ends with the goal that decreasing_tactic could not prove, ⊢ 3 * n + 1 < n, which is false. Marking the definition partial makes Lean accept it without a termination proof, and you can run it, but you cannot reason about it:

partial def collatz (n : Nat) : Nat :=
  if n ≤ 1 then 0
  else if n % 2 = 0 then 1 + collatz (n / 2)
  else 1 + collatz (3 * n + 1)
 
#eval collatz 27   -- 111
#print collatz
example : collatz 1 = 0 := by rfl

Even this one-step fact fails: Lean reports that the left-hand side collatz 1 is not definitionally equal to the right-hand side 0, and unfold collatz fails too.

Remark 4.1 (Why partial functions are opaque).

A partial def enters the logic as an opaque constant: Lean knows its type and nothing else (#print shows opaque collatz : Nat → Nat). The compiled code is used only by #eval and by programs. It has to be this way. partial def loop (n : Nat) : Nat := loop n + 1 is accepted too, and if Lean knew its equation loop 0 = loop 0 + 1, subtracting would prove 0 = 1. Lean only requires that the result type is inhabited, so the constant could exist at all.

The remark on opaque partial functions (Remark 4.1) is the price of convenience. Well-founded definitions are sealed too, more mildly: #print myGcd shows it marked @[irreducible], so rfl will not unfold it, but unfold myGcd and simp [myGcd] will.

Inductive predicates

An inductive type whose type ends in Prop defines a property by rules. Each constructor is an inference rule, and a proof is a finite tree of rule applications.

Definition 4.3 (Inductive predicate).

An inductive predicate is an inductive family P : A → Prop whose constructors are the rules for deriving P a. P holds of exactly the values that some finite derivation reaches: it is the smallest predicate closed under the rules.

inductive Ev : Nat → Prop where
  | zero : Ev 0
  | step (n : Nat) : Ev n → Ev (n + 2)
 
example : Ev 4 := Ev.step 2 (Ev.step 0 Ev.zero)

“Smallest” (Definition 4.3) is what makes such a definition useful: nothing is even unless the rules say so, and Lean lets you use that. cases h on h : Ev 1 asks which rule could have produced h. Ev.zero would need 1 = 0, and Ev.step would need 1 = n + 2, and both are impossible, so no goals are left. induction h goes further and proves a property of every derivation, one case per rule. This is often called rule induction:

theorem not_ev_one : ¬ Ev 1 := by
  intro h
  cases h
 
theorem ev_mod_two (n : Nat) (h : Ev n) : n % 2 = 0 := by
  induction h with
  | zero => rfl
  | step k _ ih => omega

Trying to derive a false instance gets stuck exactly where the rules run out:

example : Ev 3 := by
  apply Ev.step
  apply Ev.step

The first apply leaves the goal Ev 1. The second fails: Lean could not unify the conclusion of Ev.step, Ev (?n + 2), with the goal Ev 1.

Example 4.1 (Reachability).

The reflexive–transitive closure of a relation r relates a to c when c is reachable from a in zero or more r-steps. Program semantics (Lecture 9) and state machines (Lecture 10) are built on this definition.

inductive Star {α : Type} (r : α → α → Prop) : α → α → Prop where
  | refl (a : α) : Star r a a
  | step {a b c : α} : r a b → Star r b c → Star r a c
 
theorem star_trans {α : Type} {r : α → α → Prop} {a b c : α}
    (h1 : Star r a b) (h2 : Star r b c) : Star r a c := by
  induction h1 with
  | refl => exact h2
  | step hab _ ih => exact Star.step hab (ih h2)

The proof that reachability (Example 4.1) is transitive is a rule induction on the first path: an empty path changes nothing, and a path that starts with a step keeps that step in front of the joined rest.

Not every list of rules is allowed. The type being defined may appear in a constructor’s arguments only to the right of arrows (strict positivity):

inductive Bad where
  | mk : (Bad → False) → Bad

Lean refuses with (kernel) arg #1 of ‘Bad.mk’ has a non positive occurrence of the datatypes being declared. The check is not fussiness. With Bad you could apply a function Bad → False to a value built from itself and prove False with no axioms, so the kernel rejects the declaration.

Try this

  • Prove double n = 2 * n by induction. Which tactic closes the succ case once ih is in the context?
  • Prove mySum (xs ++ ys) = mySum xs + mySum ys. Induct on xs or on ys? Try both and watch where each one gets stuck.
  • Prove Ev n → Ev (n + 4) and ¬ Ev 3. For the second, cases once is not enough.
  • In Notebook 4, write myGcd by pattern matching on m (| 0, n => n and | m + 1, n => …) and see whether Lean then proves termination on its own.

Readings