16. Efficient implementations with simple specifications
A recursive definition can be easy to reason about while allocating unnecessary intermediate data. An efficient loop may require an invariant to explain its result. In Lean, a theorem can relate the efficient implementation to the simpler definition.
Start with an invariant, then optimise
The accumulator sum from Chapter 8 uses the invariant sumAcc xs acc = acc + sum xs. It describes the result for every initial accumulator, so the induction hypothesis applies to the accumulator used in each recursive call.
For a larger optimisation, keep a simple specification and prove that the new implementation agrees with it for all inputs. Callers can then reason using the specification. Measure performance separately on the compiled executable.
Lean’s compiler erases proofs. Its runtime uses reference counting and can reuse uniquely owned storage in suitable array operations. Functional source code can therefore produce efficient updates.
Sharing a value can prevent reuse, so refactoring can change allocation behaviour. Measure allocation on representative inputs.
Arrays and safe access
def readAt (values : Array Nat) (i : Fin values.size) : Nat :=
values[i.val]
def bumpAll (values : Array Nat) : Array Nat := Id.run do
let mut result := values
for i in [:result.size] do
if h : i < result.size then
result := result.set i (result[i] + 1)
return result
#eval bumpAll #[2, 4, 6]
The type of readAt includes the bound. In bumpAll, the named branch condition provides the bound for reading.
Use an optional lookup when the caller needs to handle absence. Panic-producing access treats an invalid index as an operational error. A bound in the type statically rules out that invalid access.
In addition to bounds, specify the properties relevant to the algorithm. Sorting needs ordering and element preservation, and a hash table needs a relationship between lookup and update. A numerical algorithm may need a model of overflow or approximation.
Evaluate and compile separately
#eval and lean --run are convenient during development. Use lake build and the native executable when testing operational behaviour such as stack usage, startup time, and throughput. These execution paths can differ in performance and implementation details.
Keep benchmark setup explicit: compiler version, input size and shape, build mode, and the exact executable. Compare memory use, running time, and IO behaviour separately from the theorem about equal results.
Exercises
- Explain the invariant of a loop that sums the first
iarray elements. - Extend
bumpAllto accept the increment as an argument. - Describe the properties required to verify a sorting optimisation: sortedness and preservation of elements, including multiplicities.
Once a simple specification is available, optimise only the part whose measured cost justifies the additional proof work.