Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Lean: Programs and Proofs

A program can calculate the balance after a series of transactions. A proof can establish that the calculation preserves an account invariant under stated conditions. In Lean, both use the same language: you write a function, state its contract as a type, and construct a proof of that contract.

You will begin with expressions and small functions, learn to state and prove properties, and finish with a command-line application whose central operation has a checked specification. By the end, you should be able to start a project, read library types, implement a feature, prove ordinary properties, diagnose failures, and build an executable.

Audience and prerequisites

You should already be comfortable writing programs in at least one language. Familiarity with functions, lists, branching, and command-line tools is sufficient. The book introduces functional programming, formal logic, and dependent types as needed.

The explanations are written for engineers reading English at CEFR C1 and define technical terms when they first appear.

You do not need university mathematics to follow the main route. The Mathlib chapter introduces the conventions needed to start using an existing mathematical library. Research mathematics, compiler internals, and advanced tactic implementation are separate areas of study.

What you will build

The running project is a small account model. A withdrawal either returns a new balance or an explicit failure. The final application accepts a balance and an amount, validates the input, performs the operation, and prints the result.

The central theorem shows that a successful withdrawal accounts for the entire original balance. Another theorem states when withdrawal succeeds.

The application is small enough to inspect each layer, from the input boundary and pure operation to the specification, proof, executable, and tests. The same separation applies to larger tools.

How to use the book

Read Parts I and II in order. In Part III, implement the examples before reading their proofs. Part IV combines the techniques into a project workflow.

Attempt each exercise in a separate file, then compare your solution with the answer chapter. A compiling proof with a different structure is a valid answer.

Use the Lean InfoView throughout. When a tactic fails, read the goal and local hypotheses before editing the script. When an expression fails, compare its expected and inferred types.

The checked examples target Lean 4.35.0, provided by this repository’s pinned Nix environment. All lean fences in the main chapters are checked together within each chapter, with import Std and a fresh chapter namespace. Shell transcripts and intentionally incomplete exercises use text or sh fences.

The downloadable workbook project contains the capstone as ordinary source files. Mathlib has its own toolchain; its separate verification instructions appear in the Mathlib chapter.

Learning milestones

The program computes a result, and the proof shows that the result satisfies its contract.

AfterYou should be able to do this without copying a solution
Part IModel an input with inductive types, write total recursive functions, and inspect their types and results
Part IITranslate a simple contract into a proposition and prove it with terms, rewriting, cases, or induction
Part IIIUse type classes and effects, design validated data, and connect an implementation to a specification
Part IVMaintain a Lake project, navigate dependencies, build a CLI, review trust assumptions, and diagnose failures

The tutorial draws on the source books and provides its own sequence, explanations, examples, and exercises. Sources and coverage identifies the upstream material and explains how the programming and proof material are integrated.

1. Your first checked file

Elan selects and installs toolchains. Lean checks files and executes programs. Lake resolves package dependencies, invokes the selected compiler, and builds packages.

Install and select a toolchain

Follow the official installation guide for your operating system. Install VS Code and the official Lean 4 extension. The extension provides the InfoView: a panel that displays types, messages, and the current proof state as you move the cursor.

Shell commands in this book use a Unix-like shell. On Windows, WSL provides the same command and path conventions.

For this book, create a directory containing a lean-toolchain file with this single line:

leanprover/lean4:v4.35.0

When lean is provided by Elan, running it in this directory selects that version. Confirm the compiler actually in use:

lean --version
lake --version

The first command should report version 4.35.0. If Nix supplies Lean directly, the Nix package must match the version in the file. In the deva repository, nix develop supplies the checked version.

Create First.lean, open the directory in VS Code, and enter:

#check Nat
#check Nat → Nat
#eval 19 + 23

def twice (n : Nat) : Nat := n + n

#eval twice 21
example : twice 3 = 6 := by rfl

#check asks for a type. #eval runs an expression and reports a value. Both evaluations above produce 42.

A def gives a name to an expression. An example checks a term against the stated type without giving the declaration a reusable name.

The final line is a proof. rfl succeeds because both sides reduce to the same value. The reduction establishes this particular equality.

Run the file outside the editor as well:

lean First.lean

A successful check exits with status 0. Evaluation messages appear in the output. Use the command-line check to reproduce the editor’s result.

Read the environment

Put the cursor after by in the example. The InfoView displays the goal after ⊢, showing the type of the term you still need to construct. After rfl, there should be no remaining goals.

Lean’s editor can enter Unicode through backslash abbreviations: \to for →, \alpha for α, \forall for ∀, and \vdash for ⊢. The syntax fun x => x uses ASCII, so you can write many first examples without special input. Learn the notation as it appears in the examples.

Exercises

  1. Define triple : Nat → Nat and evaluate it at 14.
  2. Prove triple 4 = 12 using rfl.
  3. Change the expected result to 13. Read the error and explain why Lean rejects it. Restore the correct statement afterwards.

You are ready to continue when you can distinguish a type-checking command, an evaluation command, a definition, and a theorem.

2. Expressions, functions, and types

Lean is expression-oriented. A function body, a conditional, and a local definition all produce values. In ordinary functional code, new values are expressions built from existing ones.

Read a declaration from left to right

def fee (amount : Nat) : Nat :=
  let base := 2
  if amount < 100 then base else base + 1

def applyTwice (f : Nat → Nat) (x : Nat) : Nat :=
  f (f x)

#eval fee 120
#eval applyTwice (fun n => n + 3) 10

amount is an explicit parameter. The type after the last colon is the result type.

:= introduces the body. The local binding base names a fixed value within the rest of the expression.

Functions are values, and fun n => n + 3 constructs one without naming it.

Function application uses spaces and associates to the left: f x y means (f x) y. Arrow types associate to the right: Nat → Nat → Nat means Nat → (Nat → Nat).

Partial application supplies some arguments to a function. Giving an addition function its first argument produces a function that takes the second.

def add (x y : Nat) : Nat := x + y

def addTen : Nat → Nat := add 10

example : addTen 7 = 17 := by rfl

Choose numerical types intentionally

Nat contains 0 and the positive whole numbers. Its subtraction truncates at 0, so 3 - 5 is 0. Int represents signed whole numbers, so (3 : Int) - 5 is -2.

UInt64 is a machine integer with bounded arithmetic. Choose the type whose arithmetic matches the quantity you are modelling.

Natural-number balances are nonnegative. To reject excessive withdrawals, check affordability explicitly and include that condition in the operation’s contract.

Literal types are inferred from context. A type annotation such as (3 : Int) tells Lean which interpretation is intended. When inference fails, add an annotation where the type first becomes ambiguous.

Polymorphism and implicit arguments

def keep {α : Type} (x : α) : α := x

#check keep
#check @keep
example : keep "account" = "account" := by rfl

α is a type parameter. Braces make it implicit, so Lean usually infers it from x.

@keep exposes implicit arguments for inspection or explicit application. Use keep (α := Nat) 7 to pass it by name.

Type itself has a type, and Lean uses a hierarchy of universes to prevent inconsistent self-reference. Write universe-polymorphic functions with universe u and α : Type u. Lean infers universe levels in most application code.

Definitions and equality

Lean can unfold the body of a definition, and a theorem names a proof. rfl proves definitional equality when both sides become the same under Lean’s computation rules.

For expressions such as n + 0 and 0 + n, the recursion rule for addition determines which expression reduces when n is a variable.

When a proof by rfl fails, ask whether both expressions reduce to the same form or whether you need an established theorem relating them.

Exercises

  1. Define a polymorphic function that chooses the first of 2 arguments of the same type.
  2. Define composition for functions α → β and β → γ.
  3. Evaluate natural and integer subtraction on the same inputs. Describe which model is appropriate for a signed temperature and which for a list length.

3. Data that describes the possibilities

Types are a design tool. A product describes values with several components, and a sum describes values that take one of several forms. Choosing those forms makes the cases explicit before you implement the program’s behaviour.

Structures: fields together

structure Account where
  owner : String
  balance : Nat
  deriving Repr, BEq

def opening : Account :=
  { owner := "Ada", balance := 100 }

def deposit (a : Account) (amount : Nat) : Account :=
  { a with balance := a.balance + amount }

#eval deposit opening 25

Account is a type with a constructor and projections such as Account.balance. Record update builds a new record, copying the unspecified fields from the original.

deriving Repr generates a representation for debugging. deriving BEq generates Boolean equality.

Boolean equality computes a result. Propositional equality expresses a claim you can prove.

Inductive types: one case at a time

inductive Request where
  | deposit (amount : Nat)
  | withdraw (amount : Nat)
  | inspect
  deriving Repr

def describe : Request → String
  | .deposit amount => s!"deposit {amount}"
  | .withdraw amount => s!"withdraw {amount}"
  | .inspect => "inspect"

Each constructor describes one form of the type and carries the data specific to it. Pattern matching makes those fields available in the corresponding branch.

Exhaustiveness checking requires the function to handle every constructor. When you add one, Lean identifies which pattern matches need a new case.

A recursive inductive type can refer to itself in its constructor fields. List α, for example, is either empty or a head of type α followed by another list. This same structure will determine both recursive programs and inductive proofs.

Failure belongs in the result type

A withdrawal that leaves a balance of 0 returns some 0. A failed withdrawal returns none.

def withdraw (balance amount : Nat) : Option Nat :=
  if amount ≤ balance then some (balance - amount) else none

#eval withdraw 100 30
#eval withdraw 20 30

def withdrawMessage (balance amount : Nat) : Except String Nat :=
  if amount ≤ balance then
    .ok (balance - amount)
  else
    .error "insufficient balance"

Option α has the constructors none and some value. It is useful when absence is the only failure information needed.

Except ε α has constructors error reason and ok value. It preserves an error value of type ε.

Returning 0 on failure would confuse an invalid withdrawal with a valid withdrawal that exhausts the balance. The sum type keeps these situations distinct. Callers must address the distinction when inspecting the result.

Use a small error inductive type once callers need to respond differently to several errors. Convert errors into human-readable strings at the UI boundary. Callers can pattern-match on the typed error and display a message for each case.

Exercises

  1. Add a frozen : Bool field to a new account structure and define a function that freezes it.
  2. Define first? : List α → Option α by pattern matching.
  3. Define an error type containing insufficientFunds and frozenAccount. Write a withdrawal function returning Except with this error type.

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

  1. Define a list function doubleEach with explicit recursion.
  2. Define the same transformation with map.
  3. 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.

5. Propositions are types of evidence

A proposition is a statement that can have a proof. In Lean, propositions inhabit Prop, and a proof of P is a term whose type is P. This is the bridge between programs and proofs: constructing a function and constructing a proof both involve producing a value of an expected type.

Lean erases proofs during compilation. Lean also treats proofs of the same proposition as indistinguishable for definitional equality, a principle called proof irrelevance.

The logical constructors

StatementRead it asConstruct its evidence by
P → QP implies QA function accepting a proof of P
P ∧ QP and QA pair of proofs
P ∨ QP or QA chosen side and its proof
¬ Pnot PA function from P to False
P ↔ QP if and only if QA proof in each direction
∀ x : α, R xR holds for every xA function accepting any x
∃ x : α, R xSome x satisfies RA witness and its proof

The following examples construct proofs directly as terms.

variable {P Q R : Prop}

theorem swapAnd (h : P ∧ Q) : Q ∧ P :=
  ⟨h.2, h.1⟩

theorem chain (hpq : P → Q) (hqr : Q → R) : P → R :=
  fun hp => hqr (hpq hp)

theorem leftChoice (hp : P) : P ∨ Q :=
  Or.inl hp

theorem existsNext (n : Nat) : ∃ m : Nat, m = n + 1 :=
  ⟨n + 1, rfl⟩

Angle brackets construct tuples or constructor values when the expected type determines which constructor is needed. h.1 and h.2 project the left and right proofs of a conjunction.

A proof of P ∧ Q gives you both component proofs. For P ∨ Q, consider each constructor in turn. For an existential, introduce a witness and its proof.

Core Lean’s cases can express these steps. Tactics such as rcases offer more compact ways to decompose evidence.

Bool, Prop, and decidability

Bool is a data type with true and false. Prop is a universe of statements. For example, n == 0 normally computes a Boolean through BEq, while n = 0 is a proposition.

A Decidable P value contains either evidence of P or evidence of ¬ P. It allows programs to branch on a proposition. Natural-number equality and order have executable decision procedures, which is why if amount ≤ balance then ... else ... works.

example : (7 : Nat) ≤ 10 := by decide
example : ¬ ((9 : Nat) = 4) := by decide

decide proves a closed decidable proposition through its decision procedure. Use it when Lean has a decision procedure it can evaluate for the goal.

Classical supplies classical principles, including noncomputable decisions for arbitrary propositions. Proofs can use classical reasoning, while executable application logic needs a computational decision procedure. Mark definitions that rely on noncomputable decisions with noncomputable.

Quantifier order is a design decision

∀ x, ∃ y, R x y allows y to depend on x. ∃ y, ∀ x, R x y requires a shared y. Decide which dependency the requirement calls for before writing the proof.

Exercises

  1. Prove P → Q → P ∧ Q as a term.
  2. Prove P ∧ Q → P.
  3. Prove ¬ P → P → Q using False.elim.
  4. Give an informal example where changing the order of ∀ and ∃ changes a true statement into a false one.

6. Tactics as controlled goal transformations

A tactic script constructs a proof term by transforming the proof state. A tactic can introduce a hypothesis, refine a target, create subgoals, or close a goal. The resulting term is checked by Lean’s kernel.

Consider the implication P ∧ Q → Q ∧ P. The tactic proof exposes the intermediate goals of the term proof from the previous chapter.

example (P Q : Prop) : P ∧ Q → Q ∧ P := by
  intro h
  constructor
  · exact h.2
  · exact h.1

intro h adds the premise to the local context. constructor applies the conjunction constructor and creates 2 goals.

Each focusing dot · starts a subproof for one goal. The first proves Q and the second proves P.

Follow the hidden state step by step

A tactic acts on the current proof state, which tracks the open goals and their local contexts. Each goal corresponds to a hole in the proof term. Use the InfoView to see how a tactic changes the goals and which hypotheses are available at each step.

Moving the cursor down the proof above produces this sequence in the InfoView:

-- after `by`
P Q : Prop
⊢ P ∧ Q → Q ∧ P

-- after `intro h`
P Q : Prop
h : P ∧ Q
⊢ Q ∧ P

-- after `constructor`
case left
P Q : Prop
h : P ∧ Q
⊢ Q

case right
P Q : Prop
h : P ∧ Q
⊢ P

-- after `· exact h.2`
case right
P Q : Prop
h : P ∧ Q
⊢ P

For each goal, the lines above ⊢ show the local variables and hypotheses. The expression after ⊢ is the type of the term needed to close that goal.

Inspect the proof term and shared metavariables

Lean builds a proof term from the tactics in a by block. Prefix a tactic or tactic sequence with show_term to see the term it constructs in the InfoView.

example (P Q : Prop) : P ∧ Q → Q ∧ P := by
  show_term
    intro h
    constructor
    · exact h.2
    · exact h.1

In the InfoView, show_term reports exact fun h => ⟨h.right, h.left⟩. Use #print on a named theorem to inspect its finished proof term. Looking at the term can reveal which constructor, function, or elimination rule a tactic applied.

Goals can also share unknown values called metavariables (displayed as ?w or ?m... in the InfoView). Solving one goal can assign a value to a metavariable that also appears in another open goal.

example (a b : Nat) (h : a = b) : ∃ x, x = a ∧ x = b := by
  apply Exists.intro
  constructor
  · rfl
  · exact h

Here apply Exists.intro introduces an unknown witness ?w : Nat. The constructor tactic then creates the goals ?w = a and ?w = b, both of which refer to that witness.

Closing the first goal with rfl assigns ?w := a. This changes the second goal to a = b, which exact h closes. Check the InfoView at the start of each branch to see whether earlier branches have resolved any shared metavariables.

A small working vocabulary

constructor creates a goal for each side of the conjunction. The proof uses h.2 for Q and h.1 for P.

TacticEffectTypical use
intro xIntroduce a function argument or assumptionImplications and universal quantifiers
exact hSupply a term of the target typeFinish a goal using known evidence
apply fMatch the conclusion of f to the target and create goals for its unresolved premisesWork backwards from a theorem
constructorApply a constructorConjunctions and similar targets
cases hSplit according to constructorsDisjunctions, options, lists, equalities
have h : P := ...Establish an intermediate factName a reusable reasoning step
change TReplace the target with a definitionally equal formExpose the intended expression
show TState the target expected at this pointMake inference and intent explicit
example (P Q R : Prop) (hpq : P → Q) (hqr : Q → R) : P → R := by
  intro hp
  have hq : Q := hpq hp
  apply hqr
  exact hq

example (P Q : Prop) (h : P ∨ Q) : Q ∨ P := by
  cases h with
  | inl hp => exact Or.inr hp
  | inr hq => exact Or.inl hq

The second proof considers the constructor that produced h. Both branches must build the same target, Q ∨ P, but they have different local evidence.

Read errors as questions about types

“Type mismatch” means the supplied term’s type differs from the expected type. Check the implicit arguments and the direction of any implication involved.

For “Unsolved goals”, inspect each remaining target and its hypotheses. For “Unknown identifier”, check imports, namespace qualification, and spelling.

If apply creates unexpected goals, inspect the theorem with #check. If a short term is hard to understand, use #check @name to expose implicit arguments. Use focusing dots to show which tactics solve each goal in a multi-goal proof.

Temporary holes and completed proofs

During exploration, sorry can stand for a missing proof. Lean may compile the file with a warning because sorry introduces an unchecked assumption.

Fill every hole and audit dependencies where the claim requires it. The workbook checker rejects sorry and admit and treats warnings as errors.

Exercises

  1. Rewrite the term proof of implication composition as a tactic proof.
  2. Prove P ∧ (Q ∧ R) → (P ∧ Q) ∧ R.
  3. Prove P ∨ Q → (P → R) → (Q → R) → R by cases.

For each proof, write down the goal before every tactic. Compare your prediction with the InfoView.

7. Equality, rewriting, and simplification

If a = b, you can substitute b for a in a property or expression. Lean can establish some equalities by computational reduction. Other equalities require a theorem or a separate argument.

Rewrite with a named fact

example (a b : Nat) (h : a = b) : a + 3 = b + 3 := by
  rw [h]

example (a b : Nat) (h : a = b) : b + 3 = a + 3 := by
  rw [← h]

rw [h] rewrites from left to right, and rw [← h] rewrites from right to left. Use rw [h] at hother to rewrite a hypothesis. Choose the direction that gives the next proof step the form it needs.

rfl closes equalities whose sides reduce to the same expression. rw applies a specific equality. simp repeatedly applies simplification rules and reductions towards a normal form.

Use simp with a visible scope

def credit (balance amount : Nat) : Nat := balance + amount

example (balance : Nat) : credit balance 0 = balance := by
  simp [credit]

example (n : Nat) : (if n = n then 8 else 9) = 8 := by
  simp

simp [credit] asks the simplifier to unfold credit, and simp [h] adds the local hypothesis h as a rule. Even with an explicit list, simp can use lemmas from the default simp set.

Temporarily replace simp with simp? to see a suggested simp only [...] invocation using the lemmas needed for that call. Use the suggestion when you want to keep the lemma dependencies explicit.

Reserve @[simp] for lemmas whose left-to-right direction gives a canonical simplification across proofs. Use simp [h] or an explicit lemma list for a local shortcut, since competing global rewrites can make proof behaviour difficult to predict.

Present a chain with calc

example (a b c : Nat) : (a + b) + c = a + (c + b) := by
  calc
    (a + b) + c = a + (b + c) := Nat.add_assoc a b c
    _ = a + (c + b) := by rw [Nat.add_comm b c]

calc organises a chain of equalities or compatible relations. Each line has its own justification. A calc proof lets readers follow an algebraic argument through its intermediate expressions.

Arithmetic automation has a domain

example (balance amount : Nat) (h : amount ≤ balance) :
    balance - amount + amount = balance := by
  omega

omega handles Presburger-style arithmetic over natural numbers and integers, including linear relationships and truncated subtraction. Use it for goals about bounds and natural-number account units.

General variable-by-variable multiplication is outside that fragment. Mathlib supplies other tools such as ring for polynomial identities and linarith for suitable linear arithmetic over ordered rings and fields.

Choose automation after identifying the mathematical theory of the goal. If a solver fails, first check whether it supports the operations in the goal.

Exercises

  1. Prove that 2 deposits can be combined: (b + x) + y = b + (x + y).
  2. Prove n ≤ n + k with omega.
  3. Define a wrapper around Option.getD and prove how it behaves on some x and none using simp with the wrapper definition.

8. Induction follows the shape of data

Evaluation handles a particular finite input. A theorem about every list needs an argument that covers lists of arbitrary size. Induction supplies that argument by following the constructors of the data.

For a list, prove the property for [], then prove it for x :: xs assuming it already holds for xs. That assumption is the induction hypothesis. It is available only for the smaller input, which is why this reasoning is justified.

A complete list proof

def count {α : Type} : List α → Nat
  | [] => 0
  | _ :: xs => count xs + 1

theorem countAppend {α : Type} (xs ys : List α) :
    count (xs ++ ys) = count xs + count ys := by
  induction xs with
  | nil => simp [count]
  | cons x xs ih =>
    simp [count, ih, Nat.add_assoc, Nat.add_comm]

In the base case, appending to an empty list leaves ys, and count [] is 0.

In the recursive case, both count and append expose the head. The induction hypothesis rewrites the count of xs ++ ys as the sum of their counts. Associativity and commutativity of addition finish the proof.

Induction supplies the hypothesis about the tail. Simplification then uses it to finish the local algebra.

The recursive call computes on the tail, and the induction hypothesis supplies evidence about that same tail.

Generalise changing parameters

Accumulator-based algorithms are a common source of weak induction hypotheses. If the recursive call changes an accumulator, the induction hypothesis must apply to every accumulator value.

def sum : List Nat → Nat
  | [] => 0
  | x :: xs => x + sum xs

def sumAcc : List Nat → Nat → Nat
  | [], acc => acc
  | x :: xs, acc => sumAcc xs (acc + x)

theorem sumAccSpec (xs : List Nat) (acc : Nat) :
    sumAcc xs acc = acc + sum xs := by
  induction xs generalizing acc with
  | nil => simp [sumAcc, sum]
  | cons x xs ih =>
    simp [sumAcc, sum, ih, Nat.add_assoc]

theorem sumAccCorrect (xs : List Nat) : sumAcc xs 0 = sum xs := by
  simpa using sumAccSpec xs 0

The strengthened statement exposes the accumulator invariant: the final answer is the initial accumulator plus the sum of the remaining list. generalizing acc prevents induction from fixing one accumulator too early.

When an induction proof fails at the recursive call, compare the call’s arguments with those in the induction hypothesis. If one argument changes, strengthen the theorem before adding tactics. A useful invariant often contains the missing generality.

Cases and induction are different

cases xs splits the proof into the empty and non-empty cases. Use it when inspecting the constructors is enough.

induction xs also supplies an induction hypothesis. Use induction when the argument needs a property of a tail, a subtree, or a smaller number.

Custom inductive types come with recursors generated from their constructors. These recursors explain why case analysis and induction work. You usually invoke them through tactics or recursive equations, but inspecting #check List.rec makes the connection explicit.

Exercises

  1. Prove count xs = xs.length by induction.
  2. Prove sum (xs ++ ys) = sum xs + sum ys.
  3. Explain why an induction hypothesis fixed at accumulator 0 cannot justify the recursive call in sumAcc.

Being able to strengthen a statement is more valuable than memorising a long tactic script.

9. Type classes and reusable interfaces

A type class is a structure whose values Lean can infer automatically when used as instance arguments. It packages operations and sometimes laws required by a generic definition, much like an interface or trait. During elaboration, instance search uses the available instances to fill in a missing term.

class Label (α : Type) where
  label : α → String

structure AccountId where
  value : Nat

instance : Label AccountId where
  label id := s!"account-{id.value}"

def display {α : Type} [Label α] (x : α) : String :=
  Label.label x

#eval display (AccountId.mk 17)

The bracketed parameter [Label α] asks Lean to find a Label instance for α. Lean infers the ordinary implicit parameter {α} from type constraints. Even when Lean knows α, instance search can fail if no suitable instance exists.

Separate an operation from its laws

BEq α supplies a Boolean comparison. A lawful interface also provides evidence that the comparison agrees with propositional equality. Generic proofs can use that evidence when reasoning about an overloaded operation.

You can define laws directly in a class:

class HasDefault (α : Type) where
  value : α

class DefaultIsZero (α : Type) [OfNat α 0] [HasDefault α] : Prop where
  valid : HasDefault.value (α := α) = 0

instance : HasDefault Nat where
  value := 0

instance : DefaultIsZero Nat where
  valid := rfl

example : HasDefault.value (α := Nat) = 0 :=
  DefaultIsZero.valid

The operation class produces data. The law class lives in Prop and supplies evidence. Larger libraries use this separation so algorithms can require only the operations they execute, while theorems request the laws they use.

Read common interfaces

Repr supports debugging output. ToString supports presentation as a string. OfNat interprets numeric literals.

HAdd supports addition, including operations with different input and output types. Functor, Applicative, and Monad describe increasingly expressive ways to organise computations.

A coercion allows Lean to insert a conversion in an expected context. This lets code use a value in a context that expects a different type. If a call becomes unclear, add a type annotation and inspect the inserted conversion with editor information or pretty-printing options.

Use a local instance when its interpretation is specific to a proof or module. Several global instances for the same type and interface can make the selected behaviour depend on priorities and imports. For application-specific meanings, a wrapper type often gives clearer instance selection.

Exercises

  1. Define a Label instance for a new UserId structure.
  2. Explain why implementing BEq by always returning true does not prove all values equal.
  3. Write a generic function that returns 2 copies of HasDefault.value in a pair.

10. Effects, monads, and IO

A pure function describes a value determined by its inputs. An IO α value describes an action that can interact with its environment and produce an α when executed. Reading a line has type IO String, which makes the effect explicit.

Start with failure propagation

def parseNat (s : String) : Except String Nat :=
  match s.toNat? with
  | some n => .ok n
  | none => .error s!"not a natural number: {s}"

def parsePair (left right : String) : Except String (Nat × Nat) := do
  let a ← parseNat left
  let b ← parseNat right
  pure (a, b)

#eval parsePair "12" "7"
#eval parsePair "bad" "7"

The arrow in let a ← ... sequences a computation and binds its successful result. If the first parse fails, the second step is skipped and the error propagates. The form let a := ... binds the computation itself without sequencing it.

The monad interface centres on pure and bind. The first puts an ordinary value into the computation context, and the second uses one computation’s result to choose the next. The do notation combines these operations with syntax for conditionals, loops, and local mutable variables.

Sequencing propagates absence in Option and errors in Except. It runs successive actions in IO. In each case, the next step can depend on the previous result.

Functor and Applicative

A failed parse skips later computations. The same do notation follows the sequencing rules of the chosen monad.

Functor.map transforms a result inside a context. Applicative applies a function produced by one computation to an argument produced by another, where the choice of argument computation is independent of the function result. Monad adds value-dependent sequencing.

#eval (fun n => n + 1) <$> (some 8)
#eval Prod.mk <$> (some 8) <*> (some "units")

The first expression produces some 9. The second combines 2 available values into an optional pair. To read these operators, check the types of map and applicative application.

Monad laws describe the expected behaviour of pure and bind. Prove the relevant laws separately when reasoning about a custom instance.

A small IO action

def greet : IO Unit := do
  let out ← IO.getStdout
  out.putStrLn "Enter an account name:"
  let input ← IO.getStdin
  let name ← input.getLine
  out.putStrLn s!"Account: {name.trimAscii.toString}"

The Unit result indicates that the action is useful for its effect. Run it through an executable’s main, #eval, or another IO action that is itself executed.

Exceptions in IO represent operational failures such as missing files. Handle expected failures at a boundary using try and catch, then decide whether to return a typed application error, report a message, or terminate. Keep domain failure distinct from a failed system operation.

Local mutation and iteration

def arrayTotal (values : Array Nat) : Nat := Id.run do
  let mut result := 0
  for value in values do
    result := result + value
  return result

example : arrayTotal #[4, 7, 9] = 20 := by decide

Id.run lets you write a pure computation using imperative syntax. Mutation stays local to the computation. Use iteration when it makes the algorithm clearer and keep a simple recursive specification for proofs.

Exercises

  1. Parse 2 natural numbers and return their sum in Except String.
  2. Write an IO action that reads a file and prints its contents. Let the path be an explicit argument.
  3. Explain why let n := parseNat s binds a value of a different type from the value bound by let n ← parseNat s inside the appropriate do block.

11. State, environments, and transformer order

As a program grows, several effects often occur together. A parser may read configuration, update a position, and report errors. Monad transformers combine these concerns while keeping their types explicit.

A state computation takes an initial state and returns a result and an updated state. A reader computation takes an environment and returns a result. A computation that can fail returns either an error or a result.

def record (amount : Nat) : StateM Nat Nat := do
  let old ← get
  set (old + amount)
  pure old

#eval (record 7).run 10

The result is (10, 17). The value 10 is the initial state, and 17 is the updated state after adding the amount. get and set read and update the state of this computation.

Combine a read-only environment with state

structure Config where
  maximum : Nat

abbrev Meter := ReaderT Config (StateM Nat)

def consume (amount : Nat) : Meter Bool := do
  let config ← read
  let used ← get
  if used + amount ≤ config.maximum then
    set (used + amount)
    pure true
  else
    pure false

#eval ((consume 4).run { maximum := 10 }).run 3

The reader supplies the configuration, and the state records usage. Pass the environment to the outer reader, then pass the initial state to the resulting computation. The output is (true, 7).

abbrev introduces a name that readily unfolds during elaboration. The abbreviation gives the transformer stack a short name while still letting Lean infer its underlying instances.

Failure and state do not commute

abbrev Rollback := StateT Nat (Except String)
abbrev Preserve := ExceptT String (StateM Nat)

def failRollback : Rollback Unit := do
  set 5
  throw "stopped"

def failPreserve : Preserve Unit := do
  set 5
  throw "stopped"

#eval failRollback.run 0
#eval failPreserve.run.run 0

In the first stack, the result has the shape Except String (Unit × Nat). The first stack returns a state only on success. The second result has the shape (Except String Unit) × Nat, so the updated state is available alongside an error.

Here “rollback” describes which pure state is available after failure. Reversing file writes or other external IO effects requires a separate mechanism. Transformer order determines which values and errors the program returns.

Both stacks update the state and then throw an error. Only the second result shape returns the final state alongside an error.

Choose the smallest useful abstraction

Pass explicit arguments when only 1 or 2 functions need configuration. Use a reader when more functions share a read-only environment, or state when passing an evolving value obscures the algorithm.

Use transformers when combining effects makes the failure and state behaviour clearer.

A stack is part of the application’s contract. Before choosing its order, write down what information should remain available after failure and check the expanded result type. Use that type to check whether callers can recover the values they need.

Exercises

  1. Modify consume so that a rejected request returns the unchanged state. Check an example that exceeds the limit.
  2. Predict the result shapes for reader-over-exception and exception-over-reader.
  3. Explain which state and error arrangement is appropriate when a caller must display how much work occurred before failure.

12. Dependent types and validated boundaries

A dependent type can mention a value. Fin n, for example, contains a natural number together with evidence that it is below n. The value of n affects which values inhabit the type.

This lets you move a validation condition into an interface. After checking an untrusted input, the rest of the program can consume a value whose type records the established condition.

Build a bounded value once

The successful branch stores evidence of the bound in Fin limit. Callers can use that evidence directly.

def bounded? (limit value : Nat) : Option (Fin limit) :=
  if h : value < limit then some ⟨value, h⟩ else none

example (i : Fin 10) : i.val < 10 := i.isLt

#eval (bounded? 10 7).map Fin.val
#eval (bounded? 10 12).map Fin.val

The named condition h is a proof available in the successful branch. The constructor ⟨value, h⟩ packages the value and its bound. The failed branch returns none because no bounded value can be constructed from that input.

A subtype {x : α // P x} similarly contains a value and a proof about it. A structure is often clearer when several fields and relationships belong together:

structure CheckedWithdrawal (balance : Nat) where
  amount : Nat
  affordable : amount ≤ balance

def remaining {balance : Nat} (request : CheckedWithdrawal balance) : Nat :=
  balance - request.amount

theorem remainingAccounts {balance : Nat}
    (request : CheckedWithdrawal balance) :
    remaining request + request.amount = balance := by
  have h := request.affordable
  simp only [remaining]
  omega

To construct a request, a caller supplies a proof that the amount is affordable. Functions receiving the request can use that proof directly. Compilation erases the proof field and retains the amount as runtime data.

Indexed families

A parameter stays uniform throughout an inductive family. An index may vary between constructors. This small vector type keeps its element type as a parameter and its length as an index:

inductive Vec (α : Type) : Nat → Type where
  | nil : Vec α 0
  | cons : α → Vec α n → Vec α (n + 1)

def Vec.head {α : Type} {n : Nat} : Vec α (n + 1) → α
  | .cons x _ => x

def Vec.map {α β : Type} (f : α → β) : Vec α n → Vec β n
  | .nil => .nil
  | .cons x xs => .cons (f x) (Vec.map f xs)

Vec.head accepts only vectors whose length is at least 1. Vec.map records that transformation preserves length. Matching refines the index so each branch can construct the required result type.

Mathematically equal index expressions can require a proof of equality. Combining lengths may therefore require arithmetic proofs and transport, which uses an equality to move a value between indexed types.

Start with ordinary data and separate theorems when dependent indices would complicate routine transformations. Use indices when they rule out errors that matter to callers.

Existentials and dependent pairs

An existential in Prop expresses that a witness exists. A dependent pair in Type, such as Sigma, stores a witness for computation along with data whose type depends on it.

Use a dependent pair when a program needs to inspect the witness at runtime. Lean erases proofs and restricts which values a program can extract from propositions.

Exercises

  1. Construct a value of Fin 5 containing 3.
  2. Write positive? : Nat → Option {n : Nat // 0 < n}.
  3. Define Vec.toList and prove or explain why Vec.head cannot be called on Vec.nil.

13. Specify behaviour before proving it

A type-correct program may still implement the wrong requirement. Verification begins by choosing a statement precise enough to express the intended behaviour. The proof comes afterwards.

A successful withdrawal accounts for the original balance. Every affordable withdrawal succeeds, and every excessive withdrawal fails. Proving only the first property would permit a broken implementation that always returns failure, because it would have no successful cases to contradict the theorem.

Define the operation and state its properties

def withdraw (balance amount : Nat) : Option Nat :=
  if amount ≤ balance then some (balance - amount) else none

theorem withdrawSuccess (balance amount : Nat) (h : amount ≤ balance) :
    withdraw balance amount = some (balance - amount) := by
  simp [withdraw, h]

theorem withdrawFailure (balance amount : Nat) (h : balance < amount) :
    withdraw balance amount = none := by
  have hn : ¬ amount ≤ balance := by omega
  simp [withdraw, hn]

theorem withdrawAccounts (balance amount result : Nat)
    (h : withdraw balance amount = some result) :
    result + amount = balance := by
  unfold withdraw at h
  split at h
  · rename_i affordable
    have same : balance - amount = result := Option.some.inj h
    omega
  · contradiction

The conservation proof uses the same case split as the implementation. In the successful branch, injectivity of some identifies the result, and arithmetic establishes conservation. In the failing branch, the hypothesis contradicts the fact that none and some result are distinct.

The theorem covers the pure function on natural-number units. Check separately that the parser, database, or external payment system uses those units and calls the function correctly.

Strengthen the success specification

theorem withdrawExact (balance amount result : Nat) :
    withdraw balance amount = some result ↔
      amount ≤ balance ∧ result = balance - amount := by
  by_cases h : amount ≤ balance
  · simp [withdraw, h, eq_comm]
  · simp [withdraw, h]

by_cases h : amount ≤ balance creates one branch with evidence of affordability and one with evidence of its negation. Supplying h to simp resolves the corresponding conditional in each branch. eq_comm aligns the direction of the result equality.

The forward direction shows that a successful withdrawal was affordable and returned the correct balance. The reverse direction shows that an affordable withdrawal returns that balance. Callers can use the equivalence to reason about the result without unfolding the definition.

Choose theorem names that reveal which operation and property they describe. A collection of small interface lemmas often survives implementation changes better than proofs scattered throughout callers that unfold every detail.

Counterexamples help improve contracts

Suppose you propose that depositing and withdrawing the same amount always returns the original balance. Specify the order: a deposit makes the subsequent withdrawal affordable, while withdrawing first requires enough funds in the original balance.

Before attempting a proof, test a balance of 0, an amount of 0, exact depletion, and excessive withdrawal.

A failed attempt can reveal that the statement is false, the available assumptions are too weak, or the proof approach is inappropriate. Separate these possibilities by evaluating concrete examples, then examining the symbolic goal.

Exercises

  1. Prove withdraw b 0 = some b.
  2. Prove withdraw b b = some 0.
  3. Prove withdraw (b + a) a = some b.
  4. Explain why conservation alone accepts an implementation that always fails.

These exercises check whether the specification covers the expected success and failure cases.

14. Projects, modules, and library navigation

A collection of checked files becomes a maintainable project when its build, imports, and toolchain are explicit. Lake supplies that structure. A project normally contains lean-toolchain, a Lake configuration, source modules, and a dependency manifest when dependencies have been resolved.

Create a package

In a new directory, with the intended Elan toolchain selected, run:

lake init workbook
lake build

Inspect the generated files before changing them. Lake supports TOML and Lean configuration files. You can copy the capstone configuration as a starting point.

Commit lean-toolchain, the Lake configuration, source files, and lake-manifest.json when it records resolved dependencies. Exclude .lake/, which contains build products and downloaded packages.

Use lake env lean File.lean to check a file in the package’s dependency environment. Use lake build for library and executable targets. Use the package build to verify that all required targets compile together.

Module names follow file paths

A file at Workbook/Core.lean is imported as Workbook.Core. An umbrella module Workbook.lean can import selected public modules. Organise code by responsibility: pure domain operations in one module, their interface theorems alongside them or in a proof module, and input/output in the executable root.

Imports load modules, and namespaces organise declaration names. Opening a namespace lets you refer to its declarations without their full qualification.

namespace Ledger

def credit (balance amount : Nat) : Nat := balance + amount

end Ledger

#check Ledger.credit

section
variable (initial : Nat)

def addReserve (amount : Nat) : Nat := initial + amount

end

#check addReserve

A section scopes local variables and settings within the current namespace. Lean includes a section variable in a declaration when the declaration uses it. Here addReserve receives the initial amount as an argument.

Find declarations by their types

Start from the goal’s main operation. For a list append theorem, use editor completion after List. to find related lemmas and jump to their definitions. Use #check to see whether a candidate’s type fits the goal.

#print shows a declaration in more detail, and #check @name exposes its implicit arguments. To inspect the elaborated details of a single command, prefix it with set_option pp.all true in.

For mathematical work, use library documentation and theorem search, then verify the discovered declaration under your installed dependency version. Search tools identify candidates. Check each candidate’s type and imports in your project.

Dependency discipline

Pin dependency revisions to make builds reproducible. Match the project’s Lean version to the versions expected by its dependencies, then use native cache files built for that toolchain.

Upgrade one layer at a time: choose the dependency revision, adopt its supported toolchain, rebuild, and address renamed declarations or changed APIs. If a proof fails after an upgrade, check whether the simplification rules have changed.

Exercises

  1. Move a pure function and its theorem into Workbook/Core.lean, then import them from another file.
  2. Put the declarations in a namespace and call them with fully qualified names.
  3. Explain why open Workbook cannot replace import Workbook.Core.

15. Becoming productive with Mathlib

Mathlib is Lean’s community library of mathematical structures, theorems, notation, and proof automation. Lean’s core and Std cover the account application. Use Mathlib when you need existing mathematical results or specialised proof tools.

Use the library’s toolchain

Create a directory called math-workbook. Add lean-toolchain containing leanprover/lean4:v4.35.0 and a lakefile.toml with this pinned configuration:

name = "math-workbook"
version = "0.1.0"

[[require]]
name = "mathlib"
scope = "leanprover-community"
git = "https://github.com/leanprover-community/mathlib4.git"
rev = "56a005855ea17e0b0958f73ec801ae140b0a1679"

Run these commands inside that directory:

MATHLIB_NO_CACHE_ON_UPDATE=1 lake update
lake exe cache get Mathlib.Tactic.Ring Mathlib.Tactic.Linarith Mathlib.Data.Rat.Defs Mathlib.Data.Set.Basic

This revision is Mathlib’s Lean 4.35.0 release. lake update resolves dependencies and creates a manifest. Commit the manifest with the configuration.

The update command above disables the automatic full-cache fetch so that the cache command can fetch prebuilt artefacts for this chapter’s imports. This avoids building all of Mathlib from source. For a different Mathlib revision, use its supported toolchain and matching cache.

If a Nix-provided toolchain reports bad .ltar file while extracting the cache, check the bundled leantar version. The book’s environment supplies 0.1.19, while the cache requires the newer format supported by 0.1.21.

Use a distribution with a compatible extractor or update the extractor in your Nix toolchain. The standard-library workbook can be checked without the Mathlib cache.

The main book’s automated check uses only Std. Save the following example as MathPractice.lean in the separate Mathlib project.

import Mathlib.Tactic.Ring
import Mathlib.Tactic.Linarith
import Mathlib.Data.Rat.Defs
import Mathlib.Data.Set.Basic

example (x y : ℤ) : (x + y) ^ 2 = x ^ 2 + 2 * x * y + y ^ 2 := by
  ring

example (x y : ℚ) (h : x ≤ y) : 3 * x + 1 ≤ 3 * y + 1 := by
  linarith

example (s t : Set ℕ) : s ∩ t ⊆ s := by
  intro x hx
  exact hx.1

Check it using lake env lean MathPractice.lean. ring normalises polynomial expressions using the relevant algebraic laws. linarith combines linear hypotheses over suitable ordered number systems.

In the subset proof, intro introduces an arbitrary element and its membership hypothesis. Membership in the intersection gives a pair of proofs, one for each set.

The proof techniques are the same as in earlier chapters. The library supplies the definitions and lemmas for common mathematical arguments.

Read mathematical notation through membership

A set s : Set α describes a predicate on values of α. To prove s ⊆ t, introduce an arbitrary x, assume x ∈ s, and prove x ∈ t. To prove set equality, use extensionality to compare membership for an arbitrary element.

Use Finset α for finite sets with computational operations. Lists preserve order and multiplicity. Choose the representation that matches the claim.

When algebraic notation is overloaded, inspect the ambient type and its class assumptions. A theorem about an arbitrary group has different available laws from one about a commutative group. A proof about natural subtraction cannot be transferred to integer subtraction merely by changing a type annotation.

Search and automation

exact? and apply? can suggest existing results. simp? can suggest an explicit list of simplification lemmas.

aesop performs structured proof search over suitable rules. norm_num proves numerical facts, ring handles polynomial identities, and linarith handles suitable linear consequences.

Use suggestions to discover an argument, then keep a readable proof with explicit dependencies where useful. Begin with one question: which existing theorem states this fact, or a stronger fact from which it follows? A theorem application is often clearer than a fresh automated derivation.

A practical search loop

  1. State the goal using the library’s existing types and operations.
  2. Inspect namespaces, documentation, and search results for the central operation.
  3. Check the candidate’s exact type in your project.
  4. Match its assumptions with your local context.
  5. Use exact, apply, rw, or simpa using to connect it to the goal.

Check the resulting proof locally.

Exercises

  1. In a Mathlib project, prove the square identity above with the summands reversed.
  2. Prove s ∩ t ⊆ t using the second membership component.
  3. Find an existing theorem for commutativity of set intersection and inspect its type before using it.

These exercises are an optional library track. Their import and version requirements are separate from the standard-library workbook.

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

  1. Explain the invariant of a loop that sums the first i array elements.
  2. Extend bumpAll to accept the increment as an argument.
  3. 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.

17. What a checked proof guarantees

Lean’s elaborator converts notation, implicit arguments, type-class instances, and tactic scripts into core expressions. The kernel checks those expressions against their types. The resulting proof term must satisfy the kernel’s checks regardless of how the tactic constructed it.

That guarantee has boundaries. The statement may omit an assumption from the real application. A definition may model a physical quantity in the wrong units.

Runtime code, foreign functions, parsing, operating systems, and external services add assumptions beyond a pure theorem.

Audit assumptions

The kernel checks that the proof term establishes the theorem under its stated assumptions.

theorem identityProof (P : Prop) : P → P := fun h => h

#print axioms identityProof

example (P : Prop) : P ∨ ¬ P := by
  classical
  exact Classical.em P

#print axioms reports the axioms on which a declaration depends transitively. An ordinary constructive identity proof needs no axioms, while classical proofs may depend on standard logical principles.

A proof using sorry depends on sorryAx, which stands for an unfinished argument.

Review logical assumptions and runtime mechanisms separately. Lean restricts unsafe declarations to uses outside trusted proofs.

noncomputable definitions can use classical existence without producing executable algorithms. Lean can run partial definitions, but treats them as opaque in proofs.

A new axiom adds an assumed constant without proving it. Use it only for a deliberate assumption in the theory.

Computation in proofs

decide can establish decidable propositions by reduction. Other mechanisms may rely on compiled computation and introduce additional trust assumptions. For an accelerated decision tactic, check its documented trust assumptions and inspect the resulting theorem’s axiom dependencies.

The account project’s theorems quantify over all mathematical inputs to the total pure function. The CLI tests exercise selected executions through parsing and output.

Equality beyond rewriting

Function extensionality, funext, proves functions equal by proving equal outputs at every input. Structure extensionality reduces equality to fields when an appropriate theorem or tactic is available. Quotients identify values through an equivalence relation, allowing mathematics to use objects determined up to that relation.

These principles explain some common dependencies printed by axiom inspection. Check what each dependency means and whether it fits the foundations you intend to use.

example (f : Nat → Nat) : (fun x => f x) = f := by
  funext x
  rfl

Exercises

  1. Inspect the axioms of a small theorem you proved by induction.
  2. Explain the difference between a theorem with a missing proof and one using classical logic.
  3. List which parts of the final CLI are covered by the conservation theorem and which are covered only by integration tests.

A useful verification claim identifies the statement, the model, the checked artefact, and the assumptions connecting it to the surrounding system.

18. Capstone: a checked account CLI

This chapter assembles a complete package. The pure core implements withdrawal and exposes its theorems. The IO boundary parses arguments, calls the core, prints the result, and returns an exit code.

The workbook tests cover properties of the core and selected behaviours of the compiled executable.

Get the complete project

Download the workbook archive, extract it, and enter the examples directory. It contains the following files:

examples/
  lean-toolchain
  lakefile.toml
  lake-manifest.json
  Workbook.lean
  Workbook/Core.lean
  Main.lean
  Tests.lean

With Elan installed, build and run:

tar -xzf workbook.tar.gz
cd examples
lake build
lake env lean -DwarningAsError=true Tests.lean
.lake/build/bin/account 100 30

The final command prints 70. Use lake build to compile the native executable and lake env lean Tests.lean to check the proofs.

Configure the package

The toolchain file selects leanprover/lean4:v4.35.0. The Lake configuration defines a library and an executable:

name = "workbook"
version = "0.1.0"
defaultTargets = ["Workbook", "account"]

[[lean_lib]]
name = "Workbook"

[[lean_exe]]
name = "account"
root = "Main"

Workbook.lean imports Workbook.Core. The lean_lib target tells Lake how to build that library. The executable target uses Main.lean as its root and produces the binary account.

Implement and verify the pure core

Theorems cover the pure operation for all natural-number inputs. Native CLI tests exercise selected parsing, output, and exit-code paths.

import Std

namespace Workbook

def withdraw (balance amount : Nat) : Option Nat :=
  if amount ≤ balance then some (balance - amount) else none

theorem withdraw_success (balance amount : Nat) (h : amount ≤ balance) :
    withdraw balance amount = some (balance - amount) := by
  simp [withdraw, h]

theorem withdraw_failure (balance amount : Nat) (h : balance < amount) :
    withdraw balance amount = none := by
  have hn : ¬ amount ≤ balance := by omega
  simp [withdraw, hn]

theorem withdraw_accounts (balance amount result : Nat)
    (h : withdraw balance amount = some result) :
    result + amount = balance := by
  unfold withdraw at h
  split at h
  · rename_i affordable
    have same : balance - amount = result := Option.some.inj h
    omega
  · contradiction

theorem withdraw_exact (balance amount result : Nat) :
    withdraw balance amount = some result ↔
      amount ≤ balance ∧ result = balance - amount := by
  by_cases h : amount ≤ balance
  · simp [withdraw, h, eq_comm]
  · simp [withdraw, h]

end Workbook

The public contract, withdraw_exact, states when a withdrawal succeeds and what balance it returns. The derived property withdraw_accounts states that the remaining balance plus the amount withdrawn equals the original balance.

The theorems quantify over all natural-number balances and amounts. Both the implementation and the proofs use the decidable comparison to distinguish affordable withdrawals from excessive ones.

The pure core returns an Option Nat. A caller that stores state should update the balance on some remaining and leave it unchanged on none.

Add the IO boundary

import Workbook

def main (args : List String) : IO UInt32 := do
  let out ← IO.getStdout
  match args with
  | [balanceText, amountText] =>
    match balanceText.toNat?, amountText.toNat? with
    | some balance, some amount =>
      match Workbook.withdraw balance amount with
      | some remaining =>
        out.putStrLn s!"{remaining}"
        pure 0
      | none =>
        out.putStrLn "insufficient balance"
        pure 1
    | _, _ =>
      out.putStrLn "expected two natural numbers"
      pure 2
  | _ =>
    out.putStrLn "usage: account BALANCE AMOUNT"
    pure 2

main accepts a list of argument strings and returns an IO action producing an exit code. The exit codes are 0 for success, 1 for insufficient balance, and 2 for an invalid invocation.

This example writes all messages to standard output. A larger Unix tool would normally send diagnostics to standard error and document that choice.

The CLI uses String.toNat? and accepts amounts as natural numbers. Currency notation, fractional amounts, and locale-specific formats would require a richer parser. A production financial model would define units, rounding, and persistence before extending this boundary.

Verify the integration

import Workbook

open Workbook

example : withdraw 100 30 = some 70 := by decide
example : withdraw 30 30 = some 0 := by decide
example : withdraw 0 0 = some 0 := by decide
example : withdraw 20 30 = none := by decide

example (balance : Nat) : withdraw balance 0 = some balance := by
  simp [withdraw]

example (balance : Nat) : withdraw balance balance = some 0 := by
  simp [withdraw]

example (balance amount : Nat) : withdraw (balance + amount) amount = some balance := by
  have h : amount ≤ balance + amount := by omega
  rw [withdraw_success _ _ h]
  congr 1
  omega

#print axioms withdraw_accounts
#print axioms withdraw_exact

The first examples check concrete core outcomes. The next examples establish generic boundary properties. Axiom inspection reports the dependencies of the central theorems.

Run these native cases as well:

Invocation argumentsOutputExit code
100 30700
30 3000
0 000
20 30insufficient balance1
bad 3expected two natural numbers2
No argumentsusage: account BALANCE AMOUNT2

The repository checker runs these 6 cases against the compiled binary to exercise argument parsing, IO, and process exit. The conservation theorem covers the pure operation for all inputs.

Extend the project independently

Add a transfer operation that returns either failure or a pair of updated balances. State and prove that a transfer preserves the combined balance and succeeds when the source has sufficient funds.

Add a command-line mode that accepts the source balance, destination balance, and amount.

Use the library search and debugging workflow to complete the extension independently. After your attempt, compare the contract and proof with the solution in the answer chapter.

You have reached the book’s practical goal when you can make this extension, explain its assumptions, build it, and test its boundaries.

19. A repeatable debugging and proof workflow

Lean development alternates between choosing a representation and proving that it supports the required properties. Use the current goal to decide what to change or prove next.

Develop a function and its contract together

Start with a small, typed definition and evaluate its boundary cases. State a property that matters to a caller and attempt a proof.

If the proof fails, check whether you need a helper lemma, a stronger invariant, or a different representation. Once proved, make the property part of the module’s interface.

Before using automation, classify the goal:

GoalFirst approach
An implication or universal statementintro
A conjunctionconstructor or a pair of terms
An existentialProvide the witness, then prove its property
A disjunction hypothesiscases
Equality after computationrfl
A known equality in a larger expressionrw
Routine normalisationsimp with relevant definitions or hypotheses
Recursive data propertyInduction, with changing parameters generalised
Natural or integer linear arithmeticomega
A library fact with slightly different notationsimpa using a checked theorem

Use the goal and its local hypotheses to decide which of these starting points applies.

When elaboration fails

Reduce the expression to the smallest failing call and inspect the function’s type. Annotate the first ambiguous value or supply an implicit argument by name. If instance search fails, check that a suitable type-class instance exists and is available through the current imports.

For a universe mismatch, check whether a function declared with Type needs to be universe-polymorphic. For a dependent index mismatch, check whether the indices are definitionally equal or need a proof of equality. If they need a proof, use it to reconcile the indices or redesign the interface if callers routinely need to transport values.

When a tactic fails

Read the goal and its local hypotheses. Identify the main connective or operation and compare the exact target type with the conclusion of the theorem you want to apply.

Check the rewrite direction and see whether simplification has already changed the expression. If the induction hypothesis fails to match the recursive call, compare their arguments and strengthen the statement as needed.

Use conversion mode to focus a rewrite on a specific part of an equality.

example (a b c : Nat) : a + (b + c) = a + (c + b) := by
  conv =>
    lhs
    arg 2
    rw [Nat.add_comm b c]

lhs selects the left side of the equality, and arg 2 then selects the second argument of its outer addition. The rewrite applies within that argument.

When a tactic behaves unexpectedly, inspect the term or the rules it uses.

  • Prefix a tactic block with show_term to see the term Lean constructs.
  • Run simp? to get a suggested simp only [...] invocation. Use it to make the lemma dependencies explicit.
  • If simp stalls or loops, put set_option trace.Meta.Tactic.simp true in immediately before the declaration to trace its rewrites in the InfoView.

When the build fails

Check the selected compiler version, the dependency manifest, and whether the command runs through lake env. If Lean cannot find a module, check that the file path matches the import and that the dependency has been built. Rebuild stale artefacts with the correct toolchain.

If stale artefacts persist, use lake clean and rebuild. The command removes local build products, so the next build may take longer. Keep the source files and manifest that define the project.

A completion checklist

Check that the public types express the intended inputs and outputs, the failure cases are explicit, and the contract specifies when the operation succeeds and what it guarantees. Check that the proofs have no holes and audit axiom dependencies where the claim requires it.

Build the package and run representative boundary tests against the native executable.

Exercises

  1. Introduce a wrong rewrite direction in a working proof and use the goal state to repair it.
  2. Move one declaration into a namespace and diagnose the resulting name-resolution error in a caller.
  3. Take one new feature through the complete loop: definition, boundary examples, contract, proof, native build, and integration test.

You are working independently when you can explain why the next step addresses the current failure, even when you still consult documentation for names and syntax.

Appendix A. Strings, parsing, and boundary design

The input boundary converts external bytes and text into the typed values the verified core accepts. It handles encoding, validation, and error reporting, and makes units explicit.

Characters and UTF-8

A Char represents a Unicode scalar value. A String stores UTF-8 text.

Byte offsets and character counts measure different things. Neither directly counts user-perceived graphemes, such as a letter followed by combining marks.

Code that assumes each character occupies 1 byte can fail on ordinary non-ASCII names.

For a simple character-based traversal, convert to a list of characters and recurse over it. For performance-sensitive slicing, use the string-position APIs of the selected Lean version and preserve their validity requirements. A character can occupy several bytes, so advance using the string-position API.

def asciiDigits (s : String) : Bool :=
  s.toList.all (fun c => '0' ≤ c && c ≤ '9')

#eval asciiDigits "4096"
#eval asciiDigits "40x6"
#eval "café".toList.length

The predicate checks for ASCII digits, so Unicode numerals and locale-specific formats need different checks. It returns true for the empty string because every element of an empty list satisfies any predicate. If the grammar requires at least 1 digit, check for an empty string separately.

Parse into a typed error

inductive InputError where
  | empty
  | notNatural (input : String)
  | aboveLimit (value limit : Nat)
  deriving Repr

def parseLimited (input : String) (limit : Nat) : Except InputError Nat := do
  if input.isEmpty then throw .empty
  let value ← match input.toNat? with
    | some n => pure n
    | none => throw (.notNatural input)
  if value ≤ limit then
    pure value
  else
    throw (.aboveLimit value limit)

#eval parseLimited "17" 100
#eval parseLimited "101" 100

Parsing establishes that the text represents a natural number. The limit check enforces a separate rule. Distinct errors let the caller tell the user whether to fix the format or change the value.

If downstream code needs the bound, preserve its proof in a subtype or checked structure.

trimAscii.toString removes surrounding ASCII whitespace. Applying it before parsing accepts inputs with surrounding whitespace that the parser alone would reject. Document and test that choice, and give the helper a name that describes what it changes.

Choose the trust boundary

A proof about the parsed natural number begins after decoding and validation. To verify the entire boundary, specify the parser’s accepted grammar and prove that successful parsing corresponds to that grammar and numerical interpretation. For many small tools, tested parsing plus a proved domain core is an appropriate first division of effort, provided the resulting claim is stated precisely.

The operating system interprets file paths. Document assumptions about filesystem permissions and race freedom separately from properties proved about path strings.

Practice

Extend the CLI to report a specific error for a negative amount. Keep the general parse error for other invalid natural-number inputs.

Decide whether a leading plus sign and surrounding whitespace are accepted. Write a table of accepted and rejected examples before changing the parser, then run each example against the compiled executable.

Appendix B. Extending syntax without changing the logic

Lean’s notation is extensible. An application can introduce a small surface language that expands into ordinary Lean expressions. Introduce notation when readers already know the concept and the shorthand helps them read the code.

Begin with a function

def twiceValue (n : Nat) : Nat := n + n

syntax "twice[" term "]" : term

macro_rules
  | `(twice[$value]) => `(twiceValue $value)

example : twice[7] = 14 := by rfl

The syntax declaration tells the parser how to recognise the new form. The macro matches the new form and builds replacement syntax. The backtick introduces a syntax quotation, and $value inserts the matched term into the replacement.

After expansion, the elaborator checks the resulting function call. Proofs about the expression use the existing definition and Lean’s logic.

Know the layers

The parser recognises the written structure, and macros transform syntax. The elaborator uses expected types, inference, and the environment to turn the resulting syntax into typed core expressions.

Tactics construct proof terms by working on goals. The kernel checks the final expressions.

For a notation that simply abbreviates an expression, a macro may be enough. A construct whose interpretation depends on the inferred type may need an elaborator. A proof procedure may need tactic code that inspects goals and constructs evidence.

Preserve ordinary APIs

Keep the underlying function available and documented. It is easier to search for a named declaration, inspect its type, and state a theorem about it than to debug a large expansion with no stable API. Use local or scoped notation when its interpretation belongs to one domain.

Macros use hygiene mechanisms to avoid accidentally capturing identifiers from their expansion context. Keep hygiene enabled when writing examples. When a macro needs to bind names or generate declarations, read the reference material on hygiene and elaboration before extending it.

The account project uses ordinary functions to express its operations. In libraries with custom notation, follow the expansion to find the underlying definitions.

Practice

Add an afterFee[amount] notation that expands into an ordinary fee function call. Prove a concrete example by reduction, then inspect the function’s type independently of the notation. Use the underlying function’s definition to justify the proof.

Exercise answers and proof patterns

These are representative solutions. Equivalent total functions and complete proofs are equally valid. Try the exercises first, then compare the structure of your reasoning with the solutions.

Chapters 1–2: first definitions

namespace First

def triple (n : Nat) : Nat := n + n + n
#eval triple 14
example : triple 4 = 12 := by rfl

def first {α : Type} (x _y : α) : α := x

def compose {α β γ : Type} (g : β → γ) (f : α → β) : α → γ :=
  fun x => g (f x)

#eval (3 : Nat) - 5
#eval (3 : Int) - 5

end First

Lean rejects an incorrect expected literal because the sides of the equality reduce to different constructor values. Use Int or another signed model for signed temperatures and Nat for list lengths.

Chapter 3: data and errors

namespace Data

structure Account where
  balance : Nat
  frozen : Bool

def freeze (a : Account) : Account := { a with frozen := true }

def first? {α : Type} : List α → Option α
  | [] => none
  | x :: _ => some x

inductive Error where
  | insufficientFunds
  | frozenAccount
  deriving Repr

def withdraw (a : Account) (amount : Nat) : Except Error Account :=
  if a.frozen then .error .frozenAccount
  else if amount ≤ a.balance then .ok { a with balance := a.balance - amount }
  else .error .insufficientFunds

end Data

The order of checks is observable: a frozen account with insufficient funds returns frozenAccount. Make this policy intentional when several errors apply.

Chapters 4 and 8: recursion and induction

namespace Recursive

def doubleEach : List Nat → List Nat
  | [] => []
  | x :: xs => (x + x) :: doubleEach xs

def doubleMap (xs : List Nat) : List Nat := xs.map (fun x => x + x)

def count {α : Type} : List α → Nat
  | [] => 0
  | _ :: xs => count xs + 1

theorem countLength {α : Type} (xs : List α) : count xs = xs.length := by
  induction xs with
  | nil => rfl
  | cons x xs ih => simp [count, ih]

def sum : List Nat → Nat
  | [] => 0
  | x :: xs => x + sum xs

theorem sumAppend (xs ys : List Nat) : sum (xs ++ ys) = sum xs + sum ys := by
  induction xs with
  | nil => simp [sum]
  | cons x xs ih => simp [sum, ih, Nat.add_assoc]

end Recursive

For an append proof, induct on the argument whose constructors drive append’s recursion. For an accumulator proof, quantify over every accumulator so the induction hypothesis applies after the accumulator changes.

Chapters 5–6: logical structure

namespace Logic

variable {P Q R : Prop}

example : P → Q → P ∧ Q := fun hp hq => ⟨hp, hq⟩
example : P ∧ Q → P := fun h => h.1
example : ¬ P → P → Q := fun hn hp => False.elim (hn hp)

example (hpq : P → Q) (hqr : Q → R) : P → R := by
  intro hp
  exact hqr (hpq hp)

example : P ∧ (Q ∧ R) → (P ∧ Q) ∧ R := by
  intro h
  exact ⟨⟨h.1, h.2.1⟩, h.2.2⟩

example : P ∨ Q → (P → R) → (Q → R) → R := by
  intro h hp hq
  cases h with
  | inl p => exact hp p
  | inr q => exact hq q

end Logic

For quantifier order, every natural number has a larger natural number, but there is no single natural number larger than every natural number. The existential witness in the first statement depends on the universally quantified input.

Chapter 7: equality

namespace Equality

example (b x y : Nat) : (b + x) + y = b + (x + y) :=
  Nat.add_assoc b x y

example (n k : Nat) : n ≤ n + k := by omega

def fallback (x : Option Nat) : Nat := x.getD 7

example (n : Nat) : fallback (some n) = n := by simp [fallback]
example : fallback none = 7 := by simp [fallback]

end Equality

Chapter 9: interfaces

namespace Interfaces

class Label (α : Type) where
  label : α → String

structure UserId where
  value : Nat

instance : Label UserId where
  label user := s!"user-{user.value}"

class HasDefault (α : Type) where
  value : α

def twoDefaults {α : Type} [HasDefault α] : α × α :=
  (HasDefault.value, HasDefault.value)

end Interfaces

An always-true Boolean comparison merely defines an unreliable comparison operation. Turning its result into evidence of equality requires a law connecting that operation to propositional equality.

Chapter 10: effects

namespace Effects

def parse (s : String) : Except String Nat :=
  match s.toNat? with
  | some n => .ok n
  | none => .error "expected a natural number"

def addParsed (a b : String) : Except String Nat := do
  let x ← parse a
  let y ← parse b
  pure (x + y)

def printFile (path : System.FilePath) : IO Unit := do
  let text ← IO.FS.readFile path
  let out ← IO.getStdout
  out.putStr text

end Effects

An ordinary let binds an Except String Nat; the monadic bind extracts a Nat on the success path and propagates failure on the other path.

Chapter 11: transformer semantics

The original consume already leaves the state unchanged on rejection. With a limit of 10, a state of 8, and a request of 4, it returns (false, 8).

In either order, running both the reader and exception layers gives a function from an environment to an error or a result. The APIs and lifting operations differ between the arrangements.

State and exception have different result types depending on their order. One arrangement returns state only on success, and the other returns state on success and failure.

Choose the state-preserving result shape when callers need to inspect progress after failure. This does not reverse or commit external IO effects.

Chapter 12: checked values

namespace Checked

def three : Fin 5 := ⟨3, by decide⟩

def positive? (n : Nat) : Option {n : Nat // 0 < n} :=
  if h : 0 < n then some ⟨n, h⟩ else none

inductive Vec (α : Type) : Nat → Type where
  | nil : Vec α 0
  | cons : α → Vec α n → Vec α (n + 1)

def Vec.toList {α : Type} : Vec α n → List α
  | .nil => []
  | .cons x xs => x :: Vec.toList xs

end Checked

The empty constructor has index 0. The input type of head requires an index of the form n + 1, which excludes the empty constructor.

Chapter 13: withdrawal boundaries

namespace Contracts

def withdraw (b a : Nat) : Option Nat :=
  if a ≤ b then some (b - a) else none

example (b : Nat) : withdraw b 0 = some b := by simp [withdraw]
example (b : Nat) : withdraw b b = some 0 := by simp [withdraw]
example (b a : Nat) : withdraw (b + a) a = some b := by
  have h : a ≤ b + a := by omega
  simp [withdraw, h]

end Contracts

An always-failing operation makes a success-implies-conservation claim vacuously true. A useful contract also establishes when success occurs.

Chapters 14–17: project and verification decisions

import loads the module’s declarations. open changes how Lean resolves unqualified names for declarations that are already available.

For Mathlib, the square identity follows from ring even if the summands are reordered. Use hx.2 to extract the proof of membership in the second set. Search for Set.inter_comm and inspect it in the installed library.

Check these answers in the Mathlib environment described in Chapter 15.

An array summation invariant relates the accumulator to the sum of the processed prefix. Its statement must also track that the current index lies between 0 and the array size. A sorting proof needs ordering and preservation of the full multiset, since equality of sets alone would lose duplicate counts.

The conservation theorem covers Workbook.withdraw over mathematical natural numbers. CLI tests exercise selected parsing, printing, and exit-code paths.

Classical axioms describe the chosen logical foundations. sorryAx marks a missing argument.

Chapter 18: transfer extension

namespace Transfer

def transfer (source destination amount : Nat) : Option (Nat × Nat) :=
  if amount ≤ source then
    some (source - amount, destination + amount)
  else
    none

theorem succeeds (s d a : Nat) (h : a ≤ s) :
    transfer s d a = some (s - a, d + a) := by
  simp [transfer, h]

theorem conserves (s d a s' d' : Nat)
    (h : transfer s d a = some (s', d')) : s' + d' = s + d := by
  unfold transfer at h
  split at h
  · rename_i affordable
    have pair := Option.some.inj h
    have hs : s - a = s' := congrArg Prod.fst pair
    have hd : d + a = d' := congrArg Prod.snd pair
    omega
  · contradiction

end Transfer

This verifies transfer of natural-number units between mathematical balances. Adding persistence, concurrency, or retries would require additional contracts. For example, the database layer would need to guarantee atomic updates to both balances.

For the CLI extension, follow the existing argument parsing and exit-code structure. Test a transfer of 0, exact depletion, insufficient funds, and invalid arguments. State which pure theorems each integration path relies on.

Working reference and glossary

Essential syntax

SyntaxMeaning
x : αx has type α
def f ... := ...A named definition with a body
theorem t : P := ...A named proof of P
example : P := ...An unnamed checked example
fun x => bodyAn anonymous function
{x : α}An implicit argument
[C α]An inferred instance argument
let x := valueBind a local value
let x ← actionSequence a monadic computation
match x with ...Inspect constructors
if h : P then ... else ...Branch with evidence for the condition
by ...Construct a term through tactics
⟨a, b⟩Constructor notation guided by the expected type
x :: xsA list head followed by its tail
#[a, b]An array literal
{x : α // P x}A value with evidence of a property

Terms worth knowing

TermMeaning
ElaborationConverts surface syntax into core expressions, resolving implicit arguments, overloaded operations, and tactic scripts
ReductionComputes an expression using Lean’s definitional rules
Definitional equalityEquality Lean recognises from its computation rules
Propositional equalityA claim such as a = b that may require a proof beyond reduction
ConstructorBuilds a value of an inductive type
RecursorDefines how to use an inductive value by handling its constructors
Structural recursionRecursion on smaller constructor fields
InductionProves a property by using corresponding hypotheses about smaller values
GoalThe type of a missing term in a proof
Local contextThe variables and hypotheses available for constructing the term
MetavariableAn unknown term or type that elaboration can assign. An unresolved metavariable may indicate missing type information
Type classPackages operations or laws for instance inference
InstanceSupplies the operations or laws required by a type class
CoercionA conversion Lean can insert to meet an expected type
UniverseA level in Lean’s hierarchy of types
MonadProvides pure and sequencing in which a later computation can depend on an earlier result
Monad transformerAdds an effect layer to another computation
Dependent typeA type that mentions a value
IndexCan vary across constructors of an inductive family
ParameterRemains uniform across constructors of an inductive family
KernelChecks core terms against their types
AxiomA constant declared without a defining proof or body
Proof erasureRemoves logical evidence from runtime code
InvariantA property preserved as a computation proceeds
SpecificationStates the observable behaviour required of an implementation

Commands to remember

lean --version
lake build
lake env lean File.lean
lake env lean -DwarningAsError=true Tests.lean
lake exe cache get

Use the cache command in projects that provide the Mathlib cache executable.

Inside a file, begin with #check name, #check @name, #print name, and #print axioms theoremName. In a proof, inspect the goal and its local context first.

Sources and coverage

This book teaches programming and proofs through a shared account model. It also covers package maintenance, a CLI with a checked contract, integration testing, and debugging, and concludes with an independent transfer exercise.

Primary sources

Use these references for further detail and to identify the versions covered in this book.

Integrated coverage

Source topicWhere it is taught here
Expressions, types, functions, structures, pattern matchingChapters 1–4
Polymorphism, universes, implicit argumentsChapters 2, 9, 12, and 14
Propositions, proofs, quantifiers, equalityChapters 5–7
Tactic proofs, interaction, conversion modeChapters 6–8 and 19
Inductive types, recursion, inductionChapters 3–4 and 8
Overloading, type classes, coercionsChapter 9
Functors, applicatives, monads, and IOChapter 10
Readers, state, exceptions, transformer orderChapter 11
Dependent programming, indices, proof-carrying dataChapter 12
Connecting programs to contractsChapters 8, 13, 16, and 18
Runtime behaviour and efficient representationsChapter 16
Classical reasoning, axioms, erasure, trustChapters 5 and 17
Project structure, dependencies, mathematical librariesChapters 14–15
Practical text handling and syntax extensionsAppendices A–B

The sequence introduces each concept before relying on it. Logical constructors follow the corresponding data constructors. The book introduces induction after recursion, dependent types after proof construction, and optimisation after proving a specification.

Validation and scope

Run nix develop --command make check from the deva repository. The command checks formatting, extracts and checks every lean fence in chapter order within its page, builds the workbook’s native executable, checks its proof file with warnings treated as errors, runs 6 CLI integration cases, and builds every mdBook. The standard-library examples target Lean 4.35.0.

The Mathlib track uses the separate pinned package described in Chapter 15. It requires its own dependency cache and check command.

The shell setup instructions assume an Elan installation. The deva development shell supplies Lean directly.

Successful completion establishes a foundation for ordinary Lean programming and proof development. Advanced mathematical formalisation, substantial tactic implementation, compiler work, concurrent systems, and production persistence require domain-specific practice beyond the examples here. In the transfer assessment, you implement a new operation, state and prove its contract, and connect it to a tested executable.