About this notebook

Companion to Lecture 2: Dependent type theory and the kernel. 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 2 says that rfl proves a = b exactly when the kernel can compute a and b to the same term, using a short list of reductions. This notebook tests that claim. You will:

  1. run one rfl proof per reduction, then predict which of nine equations rfl proves;
  2. watch computation get stuck with #reduce, and see what decide can and cannot do;
  3. build addition from the recursor Nat.rec by hand, and prove facts about it;
  4. audit the axioms behind proofs by simp, omega, classical logic and native_decide.

The header loads plain Lean plus the course’s #expr_json command, which draws proof terms in section 3. No Mathlib is needed.

import leanmagic
from leanmagic import viz
 
leanmagic.setup("import LeanFV.Tools.ExprJson")
Lean 4.35.0 ready; header `import LeanFV.Tools.ExprJson` elaborated.

1. Six ways rfl can succeed

Each line below needs one kind of reduction, named in the comment. (Unfolding notation such as + to the function behind it is δ-reduction too, and nearly every line uses it.)

-- β: substitute the argument into the function body
example : (fun x : Nat => x + 1) 2 = 3 := rfl
-- δ: unfold a definition
def double (n : Nat) : Nat := n + n
example : double 3 = 6 := rfl
-- ι: the recursor Nat.rec meets the constructors of 3
example : Nat.rec (motive := fun _ => Nat) 0 (fun _ acc => acc + 2) 3 = 6 :=
  rfl
-- ζ: replace a let by its value
example : (let x := 2; x + x) = 4 := rfl
-- η: a function equals fun x => (that function) x
example (f : Nat → Nat) : (fun x => f x) = f := rfl
-- proof irrelevance: two proofs of one proposition are equal
example (p : Prop) (h1 h2 : p) : h1 = h2 := rfl

✓ Lean accepted this (no messages)

2. Predict, then run

Core Lean defines + and * on Nat by recursion on the second argument, and ++ on lists by recursion on the first. Recursion can only take a step when the argument it recurses on is a constructor (0, n + 1, [], x :: xs), not a variable.

Before running the next cell, decide for each equation whether rfl proves it. The cell asks Lean about each one separately and prints the verdict.

candidates = [
    ("(n : Nat)", "n + 0 = n"),
    ("(n : Nat)", "0 + n = n"),
    ("(n : Nat)", "n * 0 = 0"),
    ("(n : Nat)", "0 * n = 0"),
    ("(n : Nat)", "n * 1 = n"),
    ("(n : Nat)", "n + 1 - 1 = n"),
    ("(xs : List Nat)", "[] ++ xs = xs"),
    ("(xs : List Nat)", "xs ++ [] = xs"),
    ("(a b : Nat)", "[a, b].length = 2"),
]
for binders, stmt in candidates:
    r = leanmagic.lean(f"example {binders} : {stmt} := rfl",
                       advance=False, show_output=False)
    print(f"{stmt:<20} {'rfl works' if not r.errors else 'rejected'}")
n + 0 = n            rfl works
0 + n = n            rejected
n * 0 = 0            rfl works
0 * n = 0            rejected
n * 1 = n            rejected
n + 1 - 1 = n        rfl works
[] ++ xs = xs        rfl works
xs ++ [] = xs        rejected
[a, b].length = 2    rfl works

Most verdicts follow from the rule above. n * 0 and [] ++ xs take a step because the argument the recursion looks at is a constructor; 0 + n, 0 * n and xs ++ [] are stuck on a variable. [a, b].length works because the list [a, b] is built from constructors, whatever a and b are.

The surprise is n * 1 = n. One step works: n * 1 becomes n * 0 + n, then 0 + n. And there it is stuck, on the same 0 + n as before. #reduce shows how far the computation gets. The last two lines print the same stuck term:

#reduce double 3
#reduce fun n : Nat => n + 0
#reduce fun n : Nat => 0 + n
#reduce fun n : Nat => n * 1

✓ Lean accepted this

6
fun n ↦ n
fun n ↦ (Nat.rec ⟨fun x ↦ x, PUnit.unit⟩ (fun n n_ih ↦ ⟨fun x ↦ (n_ih.1 x).succ, n_ih⟩) n).1 0
fun n ↦ (Nat.rec ⟨fun x ↦ x, PUnit.unit⟩ (fun n n_ih ↦ ⟨fun x ↦ (n_ih.1 x).succ, n_ih⟩) n).1 0

The stuck term is the recursor inside +, still waiting for its last argument n to be a constructor. This is what the kernel compares with n when you write rfl, and the two are different terms:

This cell is meant to fail:

example (n : Nat) : 0 + n = n := rfl

✗ rejected, as intended

error, line 1Type mismatch
  rfl
has type
  ?m.9 = ?m.9
but is expected to have type
  0 + n = n

The ?m in the message is a metavariable: the elaborator’s placeholder for the value rfl is about. It never got filled, because no value makes both sides of 0 + n = n the same term.

decide is computation too

decide proves a statement with no free variables by evaluating its yes/no answer in the kernel. It handles numbers that would be tedious by hand:

example : 2 ^ 10 = 1024 := by decide
theorem big_dec : 2 ^ 20 % 7 = 4 := by decide

✓ Lean accepted this (no messages)

But it cannot reason about a variable, because there is nothing to compute:

This cell is meant to fail:

example (n : Nat) : n + 0 = n := by decide

✗ rejected, as intended

error, line 1Expected type must not contain free variables
  n + 0 = n
 
Hint: Use the `+revert` option to automatically clean up and revert free variables

3. A recursor by hand

Every inductive type comes with a recursor. For Nat, Nat.rec takes a motive (what to build for each n), a value for 0, and a step from n to n + 1. Here is addition built from it, with no pattern matching:

def my_add (m n : Nat) : Nat :=
  Nat.rec (motive := fun _ => Nat) m (fun _ acc => acc + 1) n
 
#eval my_add 2 3
#eval my_add 40 2

✓ Lean accepted this

5
42

Written out by hand, with step := fun _ acc => acc + 1, the kernel’s computation of my_add 2 3 goes like this:

  my_add 2 3
  = Nat.rec 2 step 3                      δ: unfold my_add
  = step 2 (Nat.rec 2 step 2)             ι: 3 is the successor of 2
  = Nat.rec 2 step 2 + 1                  β: apply step
  = (Nat.rec 2 step 1 + 1) + 1            ι, β again
  = ((Nat.rec 2 step 0 + 1) + 1) + 1      ι, β again
  = ((2 + 1) + 1) + 1                     ι: the zero case returns m = 2
  = 5

Like +, my_add recurses on its second argument, so the same facts hold by rfl and fail by rfl:

example : my_add 2 3 = 5 := rfl
example (m : Nat) : my_add m 0 = m := rfl
example (m n : Nat) : my_add m (n + 1) = my_add m n + 1 := rfl

✓ Lean accepted this (no messages)

This cell is meant to fail:

example (n : Nat) : my_add 0 n = n := rfl

✗ rejected, as intended

error, line 1Type mismatch
  rfl
has type
  ?m.5 = ?m.5
but is expected to have type
  my_add 0 n = n

For facts that do not compute, use the recursor again, now with a motive into Prop. That is induction. The motive below is the statement my_add m k = m + k; the zero case holds by rfl, and the step applies Nat.succ (add one) to both sides of the induction hypothesis ih.

theorem my_add_eq_add (m n : Nat) : my_add m n = m + n :=
  Nat.rec (motive := fun k => my_add m k = m + k) rfl
    (fun _ ih => congrArg Nat.succ ih) n

✓ Lean accepted this (no messages)

The proof term as a tree. Each box is subterm : its type, and the edge labels name the argument each child fills. Below Nat.rec, the edge zero leads to the proof for zero, succ to the step, and t to the number n the recursion runs on. The motive is not drawn as a box, but it shows in the types: the Nat.rec box has it at n, and ih has it at the step’s variable, printed x✝ because the source named it _. The rfl box has type my_add m Nat.zero = my_add m Nat.zero, which the kernel accepts for the motive at zero, my_add m 0 = m + 0, because both sides compute to m.

fig = viz.term_tree("my_add_eq_add")
The proof term of my_add_eq_add. Nat.rec has three drawn arguments: zero (the proof rfl), succ (the step, which applies congrArg Nat.succ to the hypothesis ih) and t (the number n).

The proof term of my_add_eq_add. Nat.rec has three drawn arguments: zero (the proof rfl), succ (the step, which applies congrArg Nat.succ to the hypothesis ih) and t (the number n).

rw is built from the recursor of Eq in the same way. Lecture 2 reads this term piece by piece:

theorem rw_demo (a b : Nat) (h : a = b) : a + 1 = b + 1 := by
  rw [h]
 
#print rw_demo

✓ Lean accepted this

theorem rw_demo : ∀ (a b : Nat), a = b → a + 1 = b + 1 :=
fun a b h ↦ Eq.mpr (id (congrArg (fun _a ↦ _a + 1 = b + 1) h)) (Eq.refl (b + 1))

4. Auditing axioms

Everything above used only the kernel’s rules. Tactics such as simp and omega also use Lean’s standard axioms, classical logic uses all three, and native_decide adds an axiom of its own. The next cell proves one theorem of each kind. Two of them are flawed on purpose: one has a sorry, and one rests on a made-up axiom that is false.

theorem by_simp (p : Prop) : (p ∧ True) = p := by simp
theorem by_omega (a b : Nat) : a + b = b + a := by omega
theorem by_funext : (fun n : Nat => 0 + n) = (fun n => n) :=
  funext fun n => Nat.zero_add n
theorem by_em (p : Prop) : p ∨ ¬p := Classical.em p
theorem by_native : 2 ^ 20 % 7 = 4 := by native_decide
theorem by_sorry (n : Nat) : my_add n n = 2 * n := by sorry
 
axiom pigs_fly : 1 = 2
theorem anything (p : Prop) : p := absurd pigs_fly (by decide)

◐ accepted with sorry: goals left open

goal at line 7n : Nat
⊢ my_add n n = 2 * n

Now ask #print axioms about each theorem, from Python, and print one line per theorem:

names = ["my_add_eq_add", "big_dec", "by_simp", "by_omega", "by_funext", "by_em",
         "by_native", "by_sorry", "anything"]
for name in names:
    r = leanmagic.lean(f"#print axioms {name}", advance=False, show_output=False)
    msg = r.infos[0].data.strip()
    print(f"{name:<14} {msg.split('axioms: ')[1] if 'axioms: ' in msg else '(none)'}")
my_add_eq_add  (none)
big_dec        (none)
by_simp        [propext]
by_omega       [propext, Quot.sound]
by_funext      [Quot.sound]
by_em          [propext, Classical.choice, Quot.sound]
by_native      [by_native._native.native_decide.ax_1]
by_sorry       [sorryAx]
anything       [pigs_fly]

How to read the table:

  • (none): checked by the kernel from its rules alone, like my_add_eq_add and the decide proof big_dec.
  • propext, Quot.sound, Classical.choice: the three standard axioms. simp rewrites with equations between propositions, which needs propext; function extensionality (funext) is a theorem proved from Quot.sound.
  • an axiom with _native in its name: native_decide ran compiled code and recorded its answer as a new axiom. The kernel never checked that computation.
  • sorryAx: an unfinished proof.
  • anything else, like pigs_fly: an assumption someone added. A false one proves everything, which anything shows.

Read the list, not the check mark

anything compiled without an error and proves every proposition. Only #print axioms reveals why. When you check someone else’s Lean proof, this is the first command to run.

Try this

  • Define my_mul from Nat.rec and my_add, check my_mul 3 4 = 12 by rfl, and predict which of my_mul n 0 = 0 and my_mul 0 n = 0 holds by rfl.
  • Prove my_add 0 n = n with Nat.rec, following my_add_eq_add, and draw it with viz.term_tree.
  • Add three equations of your own to candidates in section 2, for example about List.length or String.append, and predict the verdicts before running the cell.
  • Replace by native_decide with by decide in by_native and rerun the audit. Which line of the table changes?