Preface

My book Little Bits of Common Lisp collects short, complete Common Lisp programs. This book ports fourteen of those programs to Lean 4.

Lean 4 is a functional programming language and a theorem prover. Most Lean books start with proofs. This one starts with programs. Each chapter lists one working file, explains the Lean features it uses, and shows the output.

Dear reader, you may have heard that Lean 4 is a system for mathematical proofs. This book uses it as a programming language. My interest in Lean as a programming language came from reading David Thrane Christiansen’s free book on Lean, Functional Programming in Lean, which I recommend: short, clear, and rewarding.

You can read the chapters in any order. If you are new to Lean, read “A Short Tour of Lean 4” first.

The chapters form three groups. Start with the tour and the eight pure programs, which need nothing but Lean: Bayesian inference, a triple store, BM25, a summarizer, a vector store, a Hopfield network, symbolic calculus, and automatic differentiation. The six chapters that follow call an external tool or service: Apple’s on-device model, Lightpanda, Ollama, Gemini, SPARQL, and web search. The next four chapters cover Lake, stand-alone programs, common errors, and next steps. The last chapter, which has no code, surveys how people use Lean for mathematics, software verification, and AI.

You need no Lean experience, though some functional programming helps. Every listing is an exact copy of a file that ran under Lean 4.35.0, so you get the output printed here. The helpers fixed and run repeat in several files on purpose: each file stands alone, so you can copy one without a project.

You can find my other books, software, and articles at https://markwatson.com. I have worked in the general field of AI since 1982.

What’s Up With Lean 4?

Dear reader, let’s start by comparing Lean 4 with Python.

A program is also a claim (Lean) vs. a program is an instruction (Python)

Lean uses the Curry–Howard correspondence: when a type states a claim, a term of that type is a proof of the claim. The example lines in the Hopfield and symbolic math chapters are such claims, and the file does not compile if one is false. The type checker does not warn; it rejects. In Python you learn what code means by running it, and you find errors by testing. In Lean you state what is true up front, and the compiler stops until you justify it.

Totality vs. partiality

Lean accepts a recursive function only if it can show that the function stops, or if you mark it partial. That is why query in the triple store chapter recurses on the rest of its pattern list, and Poly.deriv in the symbolic math chapter counts down a Nat. Python has no such rule: while True: is legal, and an infinite loop is a run-time bug, not a type error.

This is a design choice, not a nuisance. The rule pushes you toward folds, structural recursion, and code that follows the steps of an induction proof, the same kind of code that makes proofs easy. Python pushes you toward mutable state, sentinel loops, and exceptions. Lean’s extra checks give you guarantees; Python’s lack of them lets you try ideas fast.

Purity and explicit effects

In Lean, functions are pure by default, and IO in a type marks code that has effects, so the signature shows them. In Python any function can print, change a global, or raise an exception, and its signature says nothing. Lean lets you reason about a pure core and keep effects in a few IO functions. Python lets you put effects anywhere. Lean makes reasoning easy; Python makes doing easy.

Types as specification vs. types as annotation

Lean’s dependent types can state rules in the type itself: a vector of length n, a sorted list, a legal step in a state machine. Python’s type hints are advice: they record intent, outside tools check them if you run those tools, and they never limit what the program does. The Lean compiler enforces a type; a Python team agrees on one. Lean favors writing the spec first; Python favors writing a prototype first.

Ceremony: needed in Lean, extra in Python

The programs in this book need import Std.Data.HashMap before they can use a hash map, .toFloat wherever code mixes a Nat and a Float, and deriving Inhabited before arr[i]! compiles. BM25 computes the mean document length as (docs.map List.length).sum.toFloat / (max 1 n).toFloat; Python writes sum(map(len, docs)) / len(docs). Each extra piece records why Lean allows something: which module it loaded, which number type you use, which value an out-of-range index returns. Python treats such ceremony as cost with no payoff for scripts. Lean needs it to give a guarantee.

Two different feedback loops

In Python you write, run, look, and revise at a REPL. The loop is fast, and you learn by trying. In Lean the type checker and the kernel give the feedback. It is slower, but final: a passing check does not mean “it seemed to work”; it means “this cannot be wrong under the stated assumptions.” Python gives you more tries per hour; Lean gives each result more weight.

Who reads the code

Lean code has two readers at once, a mathematician and a machine. The same text is a computation and a proof, so it must read as an argument. Python code is for people first, as “executable pseudocode”, and for the machine second. That is why Python accepts ambiguity and Lean does not: in Lean, an ambiguity is a claim you have not proved.

How each one fails

Python fails at run time, loudly, with a traceback, so you fail fast and recover. Lean fails at compile time: it refuses to run code it cannot justify. Python expects errors and recovers from them; Lean holds that an unjustified program should not exist.