About this notebook
Companion to Lecture 4: Induction and recursion. Every cell below was executed against the course’s pinned Lean 4 + Mathlib (see
lean/lean-toolchain); each Lean result is exactly what Lean printed. Download the notebook (.ipynb)
Lecture 4 says that a proof by induction is a recursive function that returns a proof. This notebook runs such proofs one step at a time, so that you see the goals the lecture describes. You will:
- split a goal with
induction, look at the two cases, and finish the formula for; - try to prove that reversing a list twice gives it back, get stuck, and find the helper lemma that unsticks the proof;
- define “even” by two rules and prove things by taking proofs of it apart;
- write a function that needs a termination proof, and one for which nobody has one.
A gold box means Lean accepted the cell with a sorry still open, and it lists the goal
each sorry stands for. That is how this notebook shows you the goals: write sorry where
you want to look, read the box, then replace the sorry.
import leanmagic
leanmagic.setup("")Lean 4.35.0 ready; header `(empty header)` elaborated.
The empty header means plain core Lean, with no Mathlib, so the notebook starts in a few seconds. Everything below is core Lean.
1. The goals of an induction
Here is the sum
def sumTo : Nat → Nat
| 0 => 0
| n + 1 => sumTo n + (n + 1)
#eval sumTo 10✓ Lean accepted this
55
Gauss’s formula says induction n and put a sorry in each case, to see what Lean asks for.
theorem sumTo_try (n : Nat) : 2 * sumTo n = n * (n + 1) := by
induction n with
| zero => sorry
| succ k ih => sorry◐ accepted with sorry: goals left open
goal at line 3case zero
⊢ 2 * sumTo 0 = 0 * (0 + 1)
goal at line 4case succ
k : Nat
ih : 2 * sumTo k = k * (k + 1)
⊢ 2 * sumTo (k + 1) = (k + 1) * (k + 1 + 1)
Two goals, one per constructor of Nat. The zero case is the formula at 0. The succ
case has a fresh number k, the induction hypothesis ih (the formula at k), and the
formula at k + 1 to prove. As a picture:
⊢ 2 * sumTo n = n * (n + 1)
│
induction n
┌────────────────┴────────────────┐
case zero case succ
⊢ 2 * sumTo 0 = 0 * (0 + 1) ih : 2 * sumTo k = k * (k + 1)
⊢ 2 * sumTo (k + 1) = (k + 1) * (k + 1 + 1)The zero case holds by computation, so rfl closes it. In the succ case, unfold one
step of sumTo and look again.
theorem sumTo_try2 (n : Nat) : 2 * sumTo n = n * (n + 1) := by
induction n with
| zero => rfl
| succ k ih =>
simp only [sumTo]
sorry◐ accepted with sorry: goals left open
goal at line 6case succ
k : Nat
ih : 2 * sumTo k = k * (k + 1)
⊢ 2 * (sumTo k + (k + 1)) = (k + 1) * (k + 1 + 1)
The goal is now 2 * (sumTo k + (k + 1)) = (k + 1) * (k + 1 + 1): true, by ih and some
algebra. Can omega do the algebra? Not as it stands. omega works with linear
arithmetic, so a product of two expressions that both contain k is just an unknown to it.
Its error names the unknowns it used (a, b, c) and gives a “possible counterexample”.
Look at b: the whole product (k + 1) * (k + 1 + 1) is one atom, unrelated to k.
This cell is meant to fail:
theorem sumTo_try3 (n : Nat) : 2 * sumTo n = n * (n + 1) := by
induction n with
| zero => rfl
| succ k ih =>
simp only [sumTo]
omega✗ rejected, as intended
error, line 6omega could not prove the goal:
a possible counterexample may satisfy the constraints
c ≥ 0
b ≥ 0
a ≥ 0
a ≥ 0
a + c ≥ -1
2*a - b + 2*c ≤ -3
where
a := ↑(sumTo k)
b := ↑(k + 1) * ↑(k + 1 + 1)
c := ↑k
Multiply the products out first, with the distributive laws Nat.mul_add and
Nat.add_mul, and use ih to replace 2 * sumTo k. What is left is linear in the atoms,
and omega finishes. A second proof gives the algebra to grind, which normalises
expressions in commutative rings.
theorem sumTo_eq (n : Nat) : 2 * sumTo n = n * (n + 1) := by
induction n with
| zero => rfl
| succ k ih =>
simp only [sumTo, Nat.mul_add, Nat.add_mul, ih]
omega
theorem sumTo_eq' (n : Nat) : 2 * sumTo n = n * (n + 1) := by
induction n with
| zero => rfl
| succ k ih =>
simp only [sumTo]
grind✓ Lean accepted this (no messages)
#print shows that the induction tactic wrote a call to Nat.recAux, which is
Nat.rec with its cases spelled 0 and n + 1: the recursor from the lecture. The middle
of the term is long, because simp only and omega wrote it; read the first three lines
and the last one.
#print sumTo_eq✓ Lean accepted this
theorem sumTo_eq : ∀ (n : Nat), 2 * sumTo n = n * (n + 1) :=
fun n ↦
Nat.recAux (Eq.refl (2 * sumTo 0))
(fun k ih ↦
Eq.mpr
(id
(congr
(congrArg Eq
(Eq.trans (Nat.mul_add 2 (sumTo k) (k + 1))
(congr (congrArg HAdd.hAdd (Eq.trans ih (Nat.mul_add k k 1))) (Nat.mul_add 2 k 1))))
(Eq.trans (Nat.mul_add (k + 1) (k + 1) 1)
(congr
(congrArg HAdd.hAdd
(Eq.trans (Nat.mul_add (k + 1) k 1)
(congr (congrArg HAdd.hAdd (Nat.add_mul k 1 k)) (Nat.add_mul k 1 1))))
(Nat.add_mul k 1 1)))))
(Decidable.byContradiction fun a ↦ sumTo_eq._proof_1 k a))
n
2. Reversing a list twice
Define reversal by recursion on the list: the reverse of x :: xs is the reverse of xs
with x put at the end.
def rev {α : Type} : List α → List α
| [] => []
| x :: xs => rev xs ++ [x]
#eval rev [1, 2, 3, 4]✓ Lean accepted this
[4, 3, 2, 1]
Reversing twice should give the list back. Try the obvious induction and look at the
cons case after one unfolding step.
theorem rev_rev_try {α : Type} (xs : List α) : rev (rev xs) = xs := by
induction xs with
| nil => rfl
| cons x xs ih =>
simp only [rev]
sorry◐ accepted with sorry: goals left open
goal at line 6case cons
α : Type
x : α
xs : List α
ih : rev (rev xs) = xs
⊢ rev (rev xs ++ [x]) = x :: xs
Stuck. The goal is rev (rev xs ++ [x]) = x :: xs, and ih is about rev (rev xs). The
goal has rev applied to something ++ [x], and nothing we know says what that is. The
induction hypothesis is fine; the missing piece is a fact about rev and ++.
Guess it from an example: rev ([1, 2] ++ [3]) is [3, 2, 1], which is 3 :: rev [1, 2].
So the lemma should be rev (ys ++ [x]) = x :: rev ys. It has its own proof by
induction, on ys:
theorem rev_append_single {α : Type} (ys : List α) (x : α) :
rev (ys ++ [x]) = x :: rev ys := by
induction ys with
| nil => rfl
| cons y ys ih => simp [rev, ih]✓ Lean accepted this (no messages)
With the lemma, the main proof goes through. In the cons case, simp rewrites
rev (rev xs ++ [x]) to x :: rev (rev xs) with the lemma, then to x :: xs with ih.
theorem rev_rev {α : Type} (xs : List α) : rev (rev xs) = xs := by
induction xs with
| nil => rfl
| cons x xs ih => simp [rev, rev_append_single, ih]✓ Lean accepted this (no messages)
This is the common shape of a stuck induction: the hypothesis is right, but the goal
contains a combination (here rev of an append) that needs a lemma of its own. When you
are stuck, write down the subterm you cannot simplify and ask what it equals.
The standard library has the same fact for its own List.reverse:
#check @List.reverse_reverse✓ Lean accepted this
@List.reverse_reverse : ∀ {α : Type u_1} (as : List α), as.reverse.reverse = as
3. Even numbers, defined by rules
An inductive predicate lists the ways to derive a fact. Here are two rules: 0 is even,
and if n is even then so is n + 2.
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)
example : Ev 4 := by
apply Ev.step
apply Ev.step
exact Ev.zero✓ Lean accepted this (no messages)
A proof of Ev 4 is a derivation, and both proofs above build the same one:
Ev.zero : Ev 0
│ Ev.step 0
Ev 2
│ Ev.step 2
Ev 4Nothing is even unless the rules derive it. So cases h on a proof h : Ev 1 looks for a
rule that could have produced it, finds none (Ev 1 is neither Ev 0 nor Ev (n + 2)),
and closes the goal. induction h proves a property of every derivation, with one case
per rule.
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✓ Lean accepted this (no messages)
In an induction on a proof, the induction hypothesis is about the smaller derivation.
Look at the goals for “the sum of two even numbers is even”, inducting on the proof of
Ev m:
theorem ev_add_try (m n : Nat) (hm : Ev m) (hn : Ev n) : Ev (m + n) := by
induction hm with
| zero => sorry
| step k _ ih => sorry◐ accepted with sorry: goals left open
goal at line 3case zero
m n : Nat
hn : Ev n
⊢ Ev (0 + n)
goal at line 4case step
m n : Nat
hn : Ev n
k : Nat
a✝ : Ev k
ih : Ev (k + n)
⊢ Ev (k + 2 + n)
In the step case the goal is Ev (k + 2 + n) and ih : Ev (k + n). One more Ev.step
turns ih into Ev (k + n + 2), which is the goal up to reordering the sum. The zero
case is Ev (0 + n); simpa using hn simplifies 0 + n to n and then uses hn.
theorem ev_add (m n : Nat) (hm : Ev m) (hn : Ev n) : Ev (m + n) := by
induction hm with
| zero => simpa using hn
| step k _ ih =>
have e : k + 2 + n = k + n + 2 := by omega
rw [e]
exact Ev.step _ ih✓ Lean accepted this (no messages)
A false instance gets stuck exactly where the rules run out. After two apply Ev.step
steps from Ev 5 the goal is Ev 1, and no rule ends in Ev 1:
This cell is meant to fail:
example : Ev 5 := by
apply Ev.step
apply Ev.step
apply Ev.step✗ rejected, as intended
error, line 4Tactic `apply` failed: could not unify the conclusion of `Ev.step`
Ev (?n + 2)
with the goal
Ev 1
Note: The full type of `Ev.step` is
∀ (n : Nat), Ev n → Ev (n + 2)
⊢ Ev 1
Not every list of rules is a definition. If the type being defined appears to the left of
an arrow in a constructor argument, the kernel refuses it: from such a type you could
prove False with no axioms.
This cell is meant to fail:
inductive Bad where
| mk : (Bad → False) → Bad✗ rejected, as intended
error, line 1(kernel) arg #1 of 'Bad.mk' has a non positive occurrence of the datatypes being declared
4. Termination
Euclid’s algorithm recurses on n % m, which is not a piece of m or n. Lean looks for
a measure that decreases at the recursive call and does not find one by itself:
This cell is meant to fail:
def myGcd (m n : Nat) : Nat :=
if m = 0 then n else myGcd (n % m) m✗ rejected, as intended
error, line 1fail to show termination for
myGcd
with errors
failed to infer structural recursion:
Cannot use parameter m:
failed to eliminate recursive application
myGcd (n % m) m
Cannot use parameter n:
failed to eliminate recursive application
myGcd (n % m) m
Could not find a decreasing measure.
The basic measures relate at each recursive call as follows:
(<, ≤, =: relation proved, ? all proofs failed, _: no proof attempted)
m n
1) 2:23-38 ? ?
Please use `termination_by` to specify a decreasing measure.
The table in the error says which measures Lean tried (m and n) and that for both “all
proofs failed” (?). We say the measure is m and prove the step: the goal is
n % m < m, with ¬m = 0 in context from the if.
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 48 180✓ Lean accepted this
12
The Collatz function halves even numbers and sends odd n to 3n + 1. Whether it reaches
1 from every start is an open problem, so no one can supply a measure. Lean’s error ends
with the goal it could not prove, 3 * n + 1 < n, which is false.
This cell is meant to fail:
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)✗ rejected, as intended
error, line 1fail to show termination for
collatz
with errors
failed to infer structural recursion:
Cannot use parameter n:
failed to eliminate recursive application
collatz (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 : Nat
h✝¹ : ¬n ≤ 1
h✝ : ¬n % 2 = 0
⊢ 3 * n + 1 < n
partial accepts the definition without a termination proof. You can run it, but the
logic sees only an opaque constant: #print shows no body, and even collatz 1 = 0
cannot be proved by unfolding.
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
#print collatz✓ Lean accepted this
111
opaque collatz : Nat → Nat
This cell is meant to fail:
example : collatz 1 = 0 := by rfl✗ rejected, as intended
error, line 1Tactic `rfl` failed: The left-hand side
collatz 1
is not definitionally equal to the right-hand side
0
⊢ collatz 1 = 0
Why is there no measure? A measure would be a number that drops at every step. The number
of steps the function takes before it stops is the obvious candidate, and the plot below
shows how irregular it is. Each value was computed by the Lean function above, through the
#eval in the next cell.
import ast
import matplotlib.pyplot as plt
N = 300
res = leanmagic.lean(f"#eval (List.range {N + 1}).map collatz", show_output=False)
steps = ast.literal_eval(res.infos[0].data.strip())
print(f"n = 1..{N}: largest step count {max(steps)} at n = {steps.index(max(steps))}")n = 1..300: largest step count 127 at n = 231
fig, ax = plt.subplots(figsize=(6.4, 3.4))
ax.scatter(range(1, N + 1), steps[1:], s=6, color="#2c5f9e")
ax.scatter([26, 27], [steps[26], steps[27]], s=28, color="#b5523b", zorder=3)
ax.annotate(f"n = 26: {steps[26]} steps, n = 27: {steps[27]} steps",
xy=(27, steps[27]), xytext=(40, max(steps) * 1.04), fontsize=9,
color="#b5523b", arrowprops=dict(arrowstyle="-", color="#b5523b", lw=0.8))
ax.set_xlabel("start n")
ax.set_ylabel("steps until 1")
ax.set_xlim(0, N + 5)
ax.set_ylim(0, max(steps) * 1.12)
ax.spines[["top", "right"]].set_visible(False)
fig.tight_layout()
Number of steps the collatz function takes from each start n from 1 to 300, computed by Lean. Neighbouring starts can differ by about a hundred steps (highlighted: 26 takes 10, 27 takes 111), so there is no simple formula to use as a termination measure.
Try this
- Prove
double n = 2 * nfordef double : Nat → Nat | 0 => 0 | n + 1 => double n + 2. First putsorryin thesucccase and read the goal.- Prove
rev (xs ++ ys) = rev ys ++ rev xs. You will need a lemma about++and[](or the library’sList.append_assoc); find out which by getting stuck first.- Prove
¬ Ev 3. Onecasesis not enough; what does the first one leave?- Rewrite
myGcdby pattern matching (| 0, n => nand| m + 1, n => myGcd (n % (m + 1)) (m + 1)) and see whether Lean proves termination withoutdecreasing_by.