About this notebook

Companion to Lecture 8: Verified functional programs. 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 8 says that a specification is a theorem about a function, and that “sorted” means two things at once: the output is in order, and it is a rearrangement of the input. This notebook works through that claim on insertion sort. You will:

  1. write insertion sort and run it;
  2. read the specification from the course library and prove that your sort meets it;
  3. break the sort so that it drops duplicates, and see which half of the proof fails;
  4. let Plausible, a random tester, find a small input that shows the bug;
  5. use the fact that the specification has only one answer: your sort and merge sort always agree.
import leanmagic
 
leanmagic.setup("import LeanFV.Programs.Sorting\nimport Plausible")
Lean 4.35.0 ready; header `import LeanFV.Programs.Sorting` elaborated.

The header loads two things. LeanFV.Programs.Sorting is the course’s sorting library: the specification of Lecture 8, a verified insertion sort isort and a verified merge sort msort. Plausible is the random tester that Mathlib uses. There is no Mathlib, so the notebook starts in a few seconds.

1. Insertion sort

Insertion sort builds the answer one element at a time: ins x l puts x into a list l that is already sorted, just before the first element that is not smaller. The library calls these insertSorted and isort; here we write our own, under new names.

open LeanFV.Programs
 
def ins (x : Nat) : List Nat → List Nat
  | [] => [x]
  | y :: ys => if x ≤ y then x :: y :: ys else y :: ins x ys
 
def sortIns : List Nat → List Nat
  | [] => []
  | x :: xs => ins x (sortIns xs)
 
#eval sortIns [5, 2, 9, 1, 5, 6]
#eval sortIns []
#eval sortIns [3, 3, 3]

✓ Lean accepted this

[1, 2, 5, 5, 6, 9]
[]
[3, 3, 3]

Three tests pass. Tests check the inputs you thought of; the proof below checks all of them.

2. The specification, and a proof

#print shows the two definitions from the library that make up the specification.

#print Sorted
#print IsSort

✓ Lean accepted this

def LeanFV.Programs.Sorted : List Nat → Prop :=
fun l ↦ List.Pairwise (fun x1 x2 ↦ x1 ≤ x2) l
def LeanFV.Programs.IsSort : (List Nat → List Nat) → Prop :=
fun f ↦ ∀ (l : List Nat), Sorted (f l) ∧ (f l).Perm l

Sorted l says that every element is ≤ every later one (List.Pairwise). IsSort f says that for every input l, the output f l is sorted and is a permutation of l (List.Perm: the same elements, each the same number of times). As a picture:

                IsSort f  :=  ∀ l,  Sorted (f l)  ∧  (f l).Perm l
                                    ──────┬─────     ──────┬─────
                                          │                │
                    "the output is in order"      "nothing lost, nothing added"
 
      f l = []          passes the first half, fails the second
      f l = l           passes the second half, fails the first

Start with the permutation half for ins, by induction on the list. Leave a sorry in the hard case to see its goal.

theorem ins_perm_try (x : Nat) (l : List Nat) : (ins x l).Perm (x :: l) := by
  induction l with
  | nil => exact List.Perm.refl _
  | cons y ys ih =>
    unfold ins
    split
    · exact List.Perm.refl _
    · sorry

◐ accepted with sorry: goals left open

goal at line 8case cons.isFalse
x y : Nat
ys : List Nat
ih : (ins x ys).Perm (x :: ys)
h✝ : ¬x ≤ y
⊢ (y :: ins x ys).Perm (x :: y :: ys)

In the second branch x went past y, so the goal compares y :: ins x ys with x :: y :: ys. The induction hypothesis ih says ins x ys is a permutation of x :: ys. Put y in front of both sides (ih.cons y), then swap the first two elements (List.Perm.swap). Chaining the two steps with .trans closes the goal.

theorem ins_perm (x : Nat) (l : List Nat) : (ins x l).Perm (x :: l) := by
  induction l with
  | nil => exact List.Perm.refl _
  | cons y ys ih =>
    unfold ins
    split
    · exact List.Perm.refl _
    · exact (ih.cons y).trans (List.Perm.swap x y ys)

✓ Lean accepted this (no messages)

The order half is longer, because when x goes first we must show it is below every element of the rest. The proof is the same as the library’s proof of insertSorted_sorted.

theorem ins_sorted (x : Nat) (l : List Nat) (h : Sorted l) :
    Sorted (ins 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 ins
    split
    · rename_i hxy
      rw [List.pairwise_cons]
      refine ⟨?_, 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)
    · rename_i hxy
      rw [List.pairwise_cons]
      refine ⟨?_, ih h.2⟩
      intro z hz
      rcases List.mem_cons.mp ((ins_perm x ys).mem_iff.mp hz) with rfl | hz
      · omega
      · exact h.1 z hz
 
theorem sortIns_correct : IsSort sortIns := by
  intro l
  induction l with
  | nil => exact ⟨List.Pairwise.nil, List.Perm.refl _⟩
  | cons x xs ih =>
    exact ⟨ins_sorted x _ ih.1, (ins_perm x _).trans (ih.2.cons x)⟩
 
#print axioms sortIns_correct

✓ Lean accepted this

'sortIns_correct' depends on axioms: [propext, Quot.sound]

sortIns_correct is the whole specification, for every list of natural numbers. The audit lists only propext and Quot.sound, two of the three standard axioms, and no sorryAx.

3. Break the sort

Here is a plausible-looking change: when x equals y, keep only one copy. Perhaps someone wanted to remove duplicates on the way.

def insBad (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 :: insBad x ys
 
def sortBad : List Nat → List Nat
  | [] => []
  | x :: xs => insBad x (sortBad xs)
 
#eval sortBad [5, 2, 9, 1, 5, 6]

✓ Lean accepted this

[1, 2, 5, 6, 9]

The output is in order, and a quick glance would accept it. One of the two 5s is gone. Run the old permutation proof on the new code:

This cell is meant to fail:

theorem insBad_perm (x : Nat) (l : List Nat) :
    (insBad x l).Perm (x :: l) := by
  induction l with
  | nil => exact List.Perm.refl _
  | cons y ys ih =>
    unfold insBad
    split
    · exact List.Perm.refl _
    · exact (ih.cons y).trans (List.Perm.swap x y ys)

✗ rejected, as intended

error, line 9Type mismatch
  List.Perm.trans (List.Perm.cons y ih) (List.Perm.swap x y ys)
has type
  (y :: insBad x ys).Perm (x :: y :: ys)
but is expected to have type
  (if x = y then y :: ys else y :: insBad x ys).Perm (x :: y :: ys)

Lean reports a type mismatch in the last line. The term proves a statement about y :: insBad x ys, but the goal is now about if x = y then y :: ys else y :: insBad x ys: the proof breaks exactly at the new branch. A failed proof does not yet show that the code is wrong; perhaps the proof needs work. Here the claim really is false, and decide proves its negation on a small input:

example : ¬ (sortBad [3, 3]).Perm [3, 3] := by decide

✓ Lean accepted this (no messages)

The order half still holds for sortBad (try to prove it). So a function can satisfy Sorted and still be wrong, which is why the specification has two halves.

4. Let a tester find the bug

Plausible tests a statement on random inputs, then shrinks a failing input to a small one. Ask whether sortBad keeps the length of its input. The fixed seed makes the run repeatable.

This cell is meant to fail:

example : ∀ l : List Nat, (sortBad l).length = l.length := by
  plausible (config := { randomSeed := some 42 })

✗ rejected, as intended

error, line 2===================
Found a counter-example!
l := [3, 3]
issue: 1 = 2 does not hold
(2 shrinks)
-------------------

The report names an input, the failed equation, and how many shrinking steps it took to reach it. Now ask a question whose answer is yes: is the output in order?

example : ∀ l : List Nat, (sortBad l).Pairwise (· ≤ ·) := by
  plausible (config := { randomSeed := some 42 })

◐ accepted with sorry: goals left open

Unable to find a counter-example
warning, line 1declaration uses `sorry`

Passing tests are not a proof

When Plausible finds no counterexample, it leaves the goal unproved: the box above warns that the declaration uses sorry. A random test can find a bug; only a proof shows there is none.

5. The specification has one answer

Two sorted lists that are permutations of each other are equal. So any two functions that meet IsSort compute the same thing. The library proves this as IsSort.unique, which gives a theorem that would be painful to prove directly: insertion sort and merge sort always agree.

theorem sortIns_eq_msort (l : List Nat) : sortIns l = msort l :=
  IsSort.unique sortIns_correct msort_correct l
 
#eval msort [5, 2, 9, 1, 5, 6]

✓ Lean accepted this

[1, 2, 5, 5, 6, 9]

The proof never looks inside either algorithm. It uses only the two correctness theorems, which is the point of stating a specification: once proved, it is all you need to know about the function.

Try this

  • Prove ∀ l, Sorted (sortBad l). Which parts of ins_sorted change?
  • Write insDesc, which sorts in decreasing order, and state the specification it meets. Can you reuse IsSort?
  • Ask Plausible whether sortIns (sortIns l) = sortIns l. Then prove it with IsSort.unique.
  • Find the smallest input on which sortBad and sortIns differ, and check your answer with decide.