So far the objects of our theorems have been numbers, sets and qubits. Lean is also a
programming language: a def is a program you can run with #eval, and the compiler turns it
into machine code. That makes a new kind of theorem possible, one whose statement mentions a
program. To verify a program is to prove such a theorem, and the kernel that checked
Lecture 1’s proof terms checks this one in exactly the same way.
Two questions take up the whole lecture. What should the theorem say, so that proving it really means the program is right? And what does Lean need from a program before it will reason about it at all? Sorting is the running example, because everyone knows what a sort should do and, as we will see, it is easy to write a statement that says less than that.
Notebook and cheatsheet
Notebook 8: Verified sorting runs everything here, breaks the sort on purpose and watches the proof fail, and lets Plausible hunt for counterexamples. Cheatsheet: Intrinsic vs extrinsic specs, What “sorted” means, Termination, decide and native_decide.
A specification is a theorem
Definition 8.1 (Specification).A specification for a function
is a relation between inputs and outputs. The function meets the specification when . Verifying means proving that statement.
A test runs List.Pairwise R l says that R
holds between every element of l and every element after it, so a sorted list of naturals is
one where List.Pairwise (· ≤ ·) holds. The second ingredient is List.Perm l₁ l₂, written
l₁ ~ l₂ after open List, which says that one list is a rearrangement of the other: the same
elements, each the same number of times.
import Mathlib
def Sorted (l : List Nat) : Prop := l.Pairwise (· ≤ ·)
def IsSort (f : List Nat → List Nat) : Prop :=
∀ l, Sorted (f l) ∧ (f l).Perm l(Older Mathlib had List.Sorted; in v4.35 it is gone, and Mathlib states these facts with
List.Pairwise or List.SortedLE. Our own Sorted keeps the code readable.)
Why both halves? Each one alone is met by a function that does not sort. The function that
throws its input away and returns [] produces a sorted list every time, because the empty
list has no pairs to be out of order. The identity function returns a permutation of its input
every time, because every list is a rearrangement of itself. Both facts are one-line proofs:
def emptySort (_ : List Nat) : List Nat := []
theorem emptySort_sorted (l : List Nat) : Sorted (emptySort l) :=
List.Pairwise.nil
theorem id_perm (l : List Nat) : (id l).Perm l :=
List.Perm.refl lThe figure shows the two conditions as two sets of possible outputs for one input. The specification asks for the intersection, and the two broken sorts each land outside it.
The overlap in the figure has exactly one element, and that is no accident: for any input there is only one sorted rearrangement of it. We prove this at the end of the next section, and it is what makes the specification complete: any function that meets it computes the same thing as any other.
Insertion sort, proved
Insertion sort builds its answer from the back. To sort x :: xs, sort xs first, then walk
along the result and put x in front of the first element that is not smaller than it:
def insertSorted (x : Nat) : List Nat → List Nat
| [] => [x]
| y :: ys =>
if x ≤ y then x :: y :: ys else y :: insertSorted x ys
def isort : List Nat → List Nat
| [] => []
| x :: xs => insertSorted x (isort xs)
#eval isort [5, 2, 9, 1, 5, 6]Lean prints [1, 2, 5, 5, 6, 9]. Each half of the specification comes from a lemma about
insertSorted, proved by induction on the list (Lecture 4). The permutation lemma says that
inserting x gives a rearrangement of x :: l. In the step case where x moves past y, the
induction hypothesis handles the tail, and List.Perm.swap exchanges the first two elements:
theorem insertSorted_perm (x : Nat) (l : List Nat) :
(insertSorted x l).Perm (x :: l) := by
induction l with
| nil => exact List.Perm.refl [x]
| cons y ys ih =>
unfold insertSorted
split
· exact List.Perm.refl _
· exact (ih.cons y).trans (List.Perm.swap x y ys)The sortedness lemma has the same skeleton. List.pairwise_cons unfolds “sorted” one step:
a :: l is sorted exactly when a is at most every element of l and l is sorted. Each
branch of the if then needs one fact about the new head. Notice that the second branch uses
the permutation lemma to learn which elements can be in insertSorted x ys: the two halves of
the specification are independent as statements, but their proofs lean on each other.
theorem insertSorted_sorted (x : Nat) (l : List Nat)
(h : Sorted l) : Sorted (insertSorted x l) := by
induction l with
| nil => exact List.pairwise_singleton _ x
| cons y ys ih =>
unfold Sorted at *
rw [List.pairwise_cons] at h
unfold insertSorted
split
· -- x ≤ y: x goes in front, and x ≤ everything after it
rename_i hxy
refine List.pairwise_cons.mpr ⟨?_, List.pairwise_cons.mpr h⟩
intro z hz
rcases List.mem_cons.mp hz with rfl | hz
· exact hxy
· exact Nat.le_trans hxy (h.1 z hz)
· -- y < x: y stays in front, x goes into the tail
rename_i hxy
refine List.pairwise_cons.mpr ⟨?_, ih h.2⟩
intro z hz
rw [(insertSorted_perm x ys).mem_iff, List.mem_cons] at hz
rcases hz with rfl | hz
· omega
· exact h.1 z hzWith the two lemmas, the theorem about isort is two more inductions, each one line per case:
theorem isort_perm (l : List Nat) : (isort l).Perm l := by
induction l with
| nil => exact List.Perm.refl []
| cons x xs ih =>
exact (insertSorted_perm x (isort xs)).trans (ih.cons x)
theorem isort_sorted (l : List Nat) : Sorted (isort l) := by
induction l with
| nil => exact List.Pairwise.nil
| cons x xs ih => exact insertSorted_sorted x _ ih
theorem isort_correct : IsSort isort :=
fun l => ⟨isort_sorted l, isort_perm l⟩
#print axioms isort_correctLean answers 'isort_correct' depends on axioms: [propext, Quot.sound], two of the three
standard axioms, pulled in by the library lemmas and tactics we used.
Theorem 8.1 (Sorting is unique).If two lists are both sorted and each is a permutation of the other, they are equal. Hence if
and both meet IsSort, thenfor every list .
Mathlib states the first sentence as List.Perm.eq_of_sortedLE. The course library proves it
from scratch for Sorted (LeanFV.Programs.eq_of_sorted_of_perm in
lean/LeanFV/Programs/Sorting.lean), and then concludes isort_eq_msort: insertion sort and
the merge sort below return the same list, without ever comparing their code. That is what
uniqueness (Theorem 8.1) buys. A specification with a single answer pins down the
function’s input-output behaviour completely; everything else about the function, its speed
for instance, is outside the specification.
Intrinsic and extrinsic specifications
So far the program and its proof live apart: isort is ordinary code, and isort_correct is a
separate theorem about it. That style is called extrinsic. The alternative is to put the
property into the type of the function, so that the code cannot be written without the proof.
That style is called intrinsic. Lean has two everyday tools for it.
A subtype {x : α // p x} is a value of type α paired with a proof that it satisfies p.
A function that returns a subtype must hand over the proof along with the value:
def sortS (l : List Nat) : {r : List Nat // Sorted r ∧ r.Perm l} :=
⟨isort l, isort_sorted l, isort_perm l⟩
#eval (sortS [3, 1, 2]).valVector α n is an array whose length n is part of its type. A function can then demand a
non-empty vector, and Lean checks every call at compile time:
def firstOf {n : Nat} (v : Vector Nat (n + 1)) : Nat := v[0]
#eval firstOf #v[7, 8, 9]The index v[0] needs a proof that 0 < n + 1, which Lean finds by itself. Calling firstOf
on an empty vector is not a runtime error but a type error:
#eval firstOf #v[]Lean reports an Application type mismatch: #v[] has type Vector ?m.7 0 but is expected
to have type Vector ℕ (?m.2 + 1). No number plus one is zero, so no call can slip through.
The trade-off is about where the proof work happens. Intrinsic types make misuse impossible and keep the guarantee next to the data, and because proofs are erased when Lean compiles (Lecture 1’s proof irrelevance), they cost nothing at run time. But every function that builds such a value must prove the property at that moment, which couples code and proof: change the algorithm and the proofs inside it break. Extrinsic proofs keep the code plain, allow many independent theorems about one function, and can be written after the code works. Most verified code mixes the two. Lengths and bounds go into types, where Lean checks them automatically, and deep functional properties such as “sorted” stay in separate theorems.
Testing, deciding and trusting
Before investing in a proof, it is worth checking that the statement is true. Lean offers three tools, and they differ in what you have to trust.
decide proves a closed statement by evaluating it. It needs a Decidable instance, a small
program that returns true or false together with evidence. The kernel runs that program
step by step, so nothing beyond the kernel is trusted. native_decide runs the same program
compiled to machine code, which is much faster on large inputs, and the price shows up in the
axiom audit:
theorem isort_ex : isort [3, 1, 2] = [1, 2, 3] := by decide
theorem isort_ex' : isort [3, 1, 2] = [1, 2, 3] := by native_decide
#print axioms isort_ex
#print axioms isort_ex'The first answer is 'isort_ex' does not depend on any axioms. The second is
'isort_ex'' depends on axioms: [isort_ex'._native.native_decide.ax_1] (Lean generates the
name, and its numeric suffix can differ between runs in a file and in the REPL). That new axiom
asserts “the compiled program returned true”, and accepting it means trusting Lean’s
compiler and runtime as well as its kernel. The native_decide docstring says it “adds the
entire lean compiler to the trusted part”. It is not a bug to use it, but an audit
(Lecture 13) should find and question every such axiom.
Neither tactic helps with a statement about all lists, which has no finite evaluation.
Property-based testing fills that gap: generate many random inputs, check the statement on
each, and if one fails, shrink it to a small counterexample. Haskell’s QuickCheck popularised
the idea; Lean’s version is Plausible,
which Mathlib imports and which runs as the tactic plausible. Here is a realistic bug, an
insertion that silently drops an element equal to one already present:
def insertBad (x : Nat) : List Nat → List Nat
| [] => [x]
| y :: ys =>
if x < y then x :: y :: ys
else if x = y then y :: ys
else y :: insertBad x ys
def isortBad : List Nat → List Nat
| [] => []
| x :: xs => insertBad x (isortBad xs)Ask Plausible whether isortBad returns a permutation. A fixed randomSeed makes the run
repeatable:
example (l : List Nat) : (isortBad l).Perm l := by
plausible (config := { randomSeed := some 42 })It reports Found a counter-example! with l := [3, 3], found at random and then shrunk
twice: isortBad [3, 3] is [3]. Now ask whether the output is sorted:
example (l : List Nat) : (isortBad l).Pairwise (· ≤ ·) := by
plausible (config := { randomSeed := some 42 })Plausible prints Unable to find a counter-example, and Lean warns that the declaration uses
sorry. Both messages matter. The first is the “sorted alone is not a specification” lesson
again, with a bug real programmers write. The second is Lean being honest: a passed test closes
the goal with sorry, so #print axioms would list sorryAx. A test is evidence, never a
proof.
Termination
Every Lean function must terminate on every input. This is not pedantry. If Lean accepted
def f (n : Nat) : Nat := f n + 1, the equation f 0 = f 0 + 1 would be a theorem, and
subtracting f 0 from both sides proves 0 = 1. A logic that admits that is useless, so Lean
asks for a reason why each recursive definition stops.
For isort the reason is automatic. Each recursive call is on xs, a piece of the input
x :: xs; this is structural recursion, and it always terminates. Merge sort is different.
It splits the list in half with take and drop and sorts each half, and the halves are not
pieces of the list in Lean’s structural sense. Here is the merge, followed by a merge sort
whose author forgot the base case:
def merge : List Nat → List Nat → List Nat
| [], ys => ys
| xs, [] => xs
| x :: xs, y :: ys =>
if x ≤ y then x :: merge xs (y :: ys)
else y :: merge (x :: xs) ysdef msortNoGuard (l : List Nat) : List Nat :=
let half := l.length / 2
merge (msortNoGuard (l.take half)) (msortNoGuard (l.drop half))Lean refuses: fail to show termination for msortNoGuard. It reports that structural
recursion does not apply, and then shows the goal it could not prove,
sizeOf (List.take (l.length / 2) l) < sizeOf l. Lean is right, and the goal is false: on
the empty list, half is 0 and l.take 0 is [] again, so the first call loops forever.
(On a one-element list the second call, on l.drop 0, loops the same way.)
The fix is the guard that stops on short lists, together with a measure: a natural number
that every recursive call makes smaller. termination_by names it, and decreasing_by proves
that it goes down, one goal per recursive call:
def msort (l : List Nat) : List Nat :=
if h : l.length < 2 then l
else
let half := l.length / 2
merge (msort (l.take half)) (msort (l.drop half))
termination_by l.length
decreasing_by
· simp only [List.length_take]; omega
· simp only [List.length_drop]; omega
#eval msort [5, 2, 9, 1, 5, 6]The first goal is (List.take (l.length / 2) l).length < l.length, under the hypothesis
h : ¬l.length < 2; rewriting the length of take turns it into arithmetic that omega
finishes. Behind the scenes Lean turns the definition into an application of well-founded
recursion: recursion along an order with no infinite descending chains, here < on Nat.
(For this definition Lean’s own heuristics would also find the measure if you left both
clauses out; writing them down documents the argument and survives later edits.)
Lean also generates an induction principle that follows the definition, so proofs about
msort can use the same case split and the same two recursive calls. The tactic
fun_induction msort l applies it, and the course library proves msort correct that way.
For code that may genuinely loop, such as an interpreter or a server, partial def skips the
termination check, at the cost that Lean can no longer unfold the function in proofs.
Try this
- In Notebook 8, change
≤to<ininsertSortedand re-run the proofs. Which lemma breaks, and which still holds? - Write
dedupSort, which sorts and removes duplicates. State its specification withList.Pairwise (· < ·)and membership (x ∈ dedupSort l ↔ x ∈ l) instead ofPerm, and test it withplausiblebefore proving anything. - Prove
(isort l).length = l.lengthin one line fromisort_perm(look forList.Perm.length_eq). - Use
native_decideto checkisorton the reversed listList.range 500, then trydecideon the same statement and compare.
Readings
- Andrew Appel, Verified Functional Algorithms, Software Foundations vol. 3, chapters Sort and Merge. The same proofs in Rocq (Coq), with exercises.
- David Thrane Christiansen, Functional Programming in Lean, the chapters on programming with dependent types and on proving termination.
- Avigad, de Moura, Kong and Ullrich, Theorem Proving in Lean 4, ch. 8, Induction and Recursion: structural and well-founded recursion in detail.
- Koen Claessen and John Hughes, “QuickCheck: a lightweight tool for random testing of Haskell programs”, ICFP 2000, doi 10.1145/351240.351266.
- Plausible, Lean’s property-based testing library, and its README.