4. Recursion, collections, and termination
A recursive function usually follows the structure of the input. For natural numbers, handle 0 and the successor case. For lists, handle the empty list and a head followed by a tail.
Each recursive call receives a smaller part of the original value.
def total : List Nat → Nat
| [] => 0
| x :: xs => x + total xs
example : total [4, 7, 9] = 20 := by rfl
def countSome {α : Type} : List (Option α) → Nat
| [] => 0
| none :: xs => countSome xs
| some _ :: xs => countSome xs + 1
Lean accepts these definitions because each recursive call takes the tail, a structurally smaller list. Totality means that a function terminates with a result for every input in its domain. Requiring a termination argument prevents unrestricted recursion from serving as a proof of an arbitrary proposition.
Beyond structural recursion
A termination argument can also use a measure computed from the input. State that measure with termination_by and, when necessary, prove the decrease with decreasing_by.
def descend (n : Nat) : Nat :=
if h : n = 0 then
0
else
descend (n - 1) + 1
termination_by n
decreasing_by omega
example : descend 5 = 5 := by simp [descend]
The branch hypothesis h records which case applies. omega solves the natural-number arithmetic obligation showing that n - 1 < n when n ≠ 0.
The result is n. The recursion illustrates how to justify termination with an explicit measure.
Within its restrictions, partial def accepts computations without a termination proof. Lean treats these definitions as opaque in proofs. Use total functions for the pure logic you plan to verify.
Reserve partial computations for boundaries where you understand their operational behaviour.
Select a collection by its role
Lists support simple structural recursion and induction. Arrays support efficient indexed access and updates.
A Fin n index carries proof that its value is below n. An optional lookup can report an invalid index at runtime.
Sets and finite sets in mathematical libraries describe membership and related properties. The choice of representation determines what storage and operations are available.
A list traversal with map, filter, or foldl often states an algorithm more clearly than manual recursion:
def addFees (amounts : List Nat) : List Nat :=
amounts.map (fun amount => amount + 2)
def large (amounts : List Nat) : List Nat :=
amounts.filter (fun amount => amount ≥ 100)
def totalFold (amounts : List Nat) : Nat :=
amounts.foldl (fun acc amount => acc + amount) 0
#eval totalFold [10, 20, 30]
The filter expects a Boolean predicate. Lean uses the comparison’s decision procedure to compute that Boolean.
Exercises
- Define a list function
doubleEachwith explicit recursion. - Define the same transformation with
map. - Define a recursive
count : List α → Nat. Predict the induction hypotheses needed to prove how it behaves on list append.
The next part develops proofs by following exactly these recursive shapes.