← Lecture notes · Formal Verification with Lean 4

Lean 4 cheatsheet

Click any card for notes, compiled examples, step-through figures and self-tests.

M1 Lean syntax & commands

A Lean file is a sequence of commands (def, theorem, #check, #eval), each checked in order against the environment built so far.

Installing Lean, starting a project

elan installs Lean and picks the version each project pins. lake new demo math creates a project that depends on Mathlib; lake exe cache get downloads Mathlib prebuilt. In VS Code, the infoview shows the goal at the cursor.

details ›

Commands: def, theorem, #check, #eval

def adds a definition, theorem a named proof of a proposition, example a proof without a name. #check e shows the type of e, #eval e runs it, #print n shows a declaration, #print axioms n lists what a proof relies on.

details ›

Functions, application, implicit arguments

fun x => e is a function; f a b applies it, meaning (f a) b. Binders: (x : α) explicit, {α : Type} implicit (Lean infers it), [Add α] found by type-class search. @f makes every argument explicit.

details ›

inductive, structure and match

inductive lists the constructors of a new type, and those are the only ways to build its values. structure is an inductive type with one constructor and named fields; ⟨a, b⟩ builds one. match takes a value apart, one case per constructor.

details ›

namespace, section, variable, open

namespace N … end N puts N. in front of every name declared inside. open N lets you drop the prefix. Dot notation h.symm means Eq.symm h, because h’s type is an Eq. variable declares arguments shared by a section.

details ›

Sources: Lectures 0–1; TPIL ch. 2

M2 Propositions as types

A proposition is a type and a proof is a term of that type, so checking a proof is checking a type.

The Curry–Howard dictionary

A proposition is a type; a proof is a term of that type. → is a function, ∧ a pair, ∨ a tagged choice, ∀ a dependent function, ∃ a (witness, proof) pair, ¬P is P → False.

details ›

And, Or, Iff: build and take apart

p ∧ q is a pair: build ⟨hp, hq⟩, use h.1, h.2. p ∨ q is one of two tagged cases: build Or.inl hp or Or.inr hq, use it by cases (h.elim). p ↔ q is a pair of implications.

details ›

∀ is a function, ∃ is a pair

A proof of ∀ x : α, P x is a function: give it any x, get a proof of P x. A proof of ∃ x, P x is a pair ⟨w, hw⟩ of a witness and a proof about it; take one apart with obtain ⟨x, hx⟩ := h.

details ›

Type checking is proof checking

your file:elaborator(big, untrusted)syntaxtactics · simp · unificationtrusted computing basekernel: isin the environmentaccepted

Checking t : T is a mechanical algorithm. If T is a statement and t a candidate proof, checking the proof is just type checking, done by a small kernel you can trust, audit or re-implement.

details ›

Negation is a function to False

¬p is defined as p → False. To prove ¬p, assume p and derive False. False has no constructors, so from h : False anything follows: False.elim h, absurd hp hnp, or nomatch h.

details ›

Classical logic and its axioms

Lean’s core rules are constructive. Classical.em p : p ∨ ¬p is a theorem built on the axiom Classical.choice; proof by contradiction and by_cases on an arbitrary p use it. #print axioms shows whether a proof did.

details ›

Sources: Lecture 1; TPIL ch. 3; Wadler 2015

M3 Type theory & the kernel

A few rules carry everything: universes, dependent functions, inductive types and definitional equality, all re-checked by a small kernel.

Universes: Prop, Type and Sort

Prop = Sort 0Type = Sort 1Nat, Bool, Nat → Nat, List Nat, PropProp : TypeType 1 = Sort 2Type, Nat → Type, List TypeType : Type 1Type 2, Type 3, …Type : Type is refused

Every type has a type: Nat : Type, Prop : Type, Type : Type 1. Lean writes Sort 0 for Prop and Sort (u+1) for Type u. Prop is special: ∀ p : Prop, p is again a Prop, and any two proofs of a Prop are equal.

details ›

Inductive types and their recursors

Declaring an inductive type gives its constructors and one recursor, such as Nat.rec. The recursor is the only primitive way to use a value. Structural recursion and proof by induction both compile to it.

details ›

Definitional equality and rfl

Two terms are definitionally equal when they compute to the same term: unfold definitions (δ), apply functions (β), run recursors on constructors (ι), substitute let (ζ), and fun x => f x ≡ f (η). rfl proves exactly these equations.

details ›

Equality is an inductive type

a = b is an inductive proposition with one constructor, Eq.refl a : a = a. Its recursor is substitution: from h : a = b and hp : P a, h ▸ hp : P b. The rw tactic builds terms of exactly this kind (Eq.mpr).

details ›

The elaborator: holes, unification, instances

stageterm so faryou writea + bcontext: a b : Natholes@HAdd.hAdd ?A ?B ?C ?i a b+ is notation; 4 implicit argumentsunification@HAdd.hAdd Nat Nat ?C ?i a b?A := Nat, ?B := Nat (types of a, b)instances@HAdd.hAdd Nat Nat Nat inst a b?i := inst, an instance of HAdd Nat Nat ?C; ?C := Natkernel@HAdd.hAdd Nat Nat Nat(@instHAdd Nat instAddNat) a b

The elaborator turns what you type into an explicit kernel term. Implicit arguments become holes ?m, unification solves them from surrounding types, and type-class search fills […] arguments. set_option pp.explicit true shows the result.

details ›

Axioms and the trusted base

Lean’s logic adds three axioms: propext, Quot.sound and Classical.choice. #print axioms t lists every axiom a proof of t depends on. sorryAx means an unfinished proof; a name containing _native means compiled code was trusted.

details ›

Sources: Lecture 2; TPIL ch. 7, 12

M4 Tactics: shaping the goal

Tactics are programs that build the proof term for you, one goal at a time.

intro, exact, apply

tacticgoalterm built so far(start)?_intro hpfun hp ↦ ?_apply hqrfun hp ↦ hqr ?_apply hpqfun hp ↦ hqr (hpq ?_)exact hpno goals ✓fun hp ↦ hqr (hpq hp)context throughout: hpq : p → q, hqr : q → r

intro h turns a goal P → Q into goal Q with h : P in context (a fun). exact t closes the goal with the term t. apply f works backwards: goal Q and f : P → Q leave goal P.

details ›

constructor, cases, rcases, obtain

The shape decides the tactic. A goal p ∧ q or p ↔ q splits with constructor. A hypothesis is taken apart by a pattern: obtain ⟨hp, hq⟩ := h for ∧ and ∃, rcases h with hp | hq for ∨.

details ›

Structured proofs: have, show, suffices, calc

have h : P := proof proves a fact and adds it to the context. show P restates the goal in a definitionally equal form. suffices h : P reduces the goal to P. calc chains steps a = b, b < c, … into one relation.

details ›

Witnesses: use, exists, refine

To prove ∃ x, P x, supply a witness a and then prove P a: use a (Mathlib), exists a (core), or refine ⟨a, ?_⟩. In refine, ?_ becomes a new goal, and _ must be found by unification.

details ›

induction and its goal states

case zerocase succk : Nat, ih : 0 + k = kinduction nrflNat.recAux (Eq.refl (0 + 0)) (fun k ih ↦ …) nthe proof term: one argument per case

induction n with | zero => … | succ k ih => … proves a goal for every n : Nat from two cases: n = 0, and n = k + 1 assuming ih, the goal for k. Write generalizing x when x must change in ih.

details ›

Focusing: ·, case, next, <;>, all_goals

The proof state is a list of goals, and a tactic works on the first. · focuses on one goal and must close it. case tag => and next => pick a goal by name or in order. t <;> s runs s on every goal that t creates.

details ›

Sources: Lecture 3; TPIL ch. 5

M5 Rewriting & automation

Rewriting and decision procedures close goals whose proofs are long but boring; know what each can and cannot do.

rw: rewriting with an equation

movewhat rw has so fargoalrw [h]: replace every a by babstractmotive := fun _a ↦ _a + 1 = b + 1each a in the goal becomes the variable _acongrArg(a + 1 = b + 1) = (b + 1 = b + 1)congrArg motive h: the old goal equals the new oneEq.mpra proof of the new goal gives one of the oldrflEq.mpr (id (congrArg motive h))(Eq.refl (b + 1))

rw [h] with h : a = b replaces every a in the goal by b, then tries rfl. rw [← h] rewrites right to left, and rw [h] at h' rewrites a hypothesis. It cannot rewrite under fun, ∀ or ∃ when the match mentions the bound variable.

details ›

simp and simp lemmas

simp rewrites with every lemma tagged @[simp], left to right, until nothing changes. simp [h, f] adds the equation h and the definition f; simp only [l] uses only l. simp? prints the simp only call that would do the same job.

details ›

decide, native_decide and kernel reduction

decide proves a proposition p that has a Decidable p instance by computing that instance to isTrue. It needs a closed goal: no free variables and no ∀ n : Nat. native_decide computes with compiled code instead and adds an axiom.

details ›

Arithmetic: omega, linarith, ring, norm_num

Each tactic handles one kind of problem. omega: linear arithmetic over ℕ, ℤ. linarith: linear inequalities from hypotheses, over ordered rings like ℝ. ring: commutative-ring identities, no hypotheses. norm_num: numerals.

details ›

exact?, apply?, aesop, grind

exact? searches the library for a lemma that closes the goal; apply? and rw? also offer partial steps. All print Try this:, to paste in. aesop searches with rules such as simp and intro; grind reasons with equalities and arithmetic.

details ›

Writing your own tactic: macro and elab

macro "name" : tactic => `(tactic| …) defines a tactic that expands to other tactics. elab "name" : tactic => do … runs Lean code in the TacticM monad: read the goal, inspect the context, assign a proof term or throw an error.

details ›

Sources: Lectures 3, 11; Lean reference manual

M6 Mathlib & search

Mathlib organises its theorems with type classes; finding the right lemma is half the work.

Type classes and the algebraic hierarchy

A type class is an interface: class Mul α declares *, and an instance supplies it for one type. Writing a * b makes Lean search for an instance. A hypothesis [Group G] brings the group laws and every lemma Mathlib proves from them.

details ›

Coercions and casts: ↑, push_cast, norm_cast

When a value of one type is used where another is expected, Lean inserts a coercion ↑: for n : ℕ, (n : ℝ) is Nat.cast n. push_cast moves casts toward the variables; norm_cast and exact_mod_cast close goals that differ only by casts.

details ›

Finset, ∑ and ∏

∑ i ∈ Finset.range n, f i is : range n stops before n. Prove sum formulas by induction on n, peeling off the last term with Finset.sum_range_succ; ∏ works the same way.

details ›

Limits as filters: Tendsto

Mathlib states every limit as Tendsto f l₁ l₂: sends sets that are large for l₁ into sets large for l₂. Tendsto u atTop (𝓝 a) is ; other filters give , or , with the same lemmas.

details ›

Matrices, vectors and the Kronecker product

Matrix (Fin 2) (Fin 2) ℂ is a function Fin 2 → Fin 2 → ℂ; write one as !![0, 1; 1, 0]. After open Matrix Kronecker, A *ᵥ v applies it to a vector, Aᴴ is the conjugate transpose and A ⊗ₖ B the Kronecker product.

details ›

Sources: Lecture 6; MIL

M7 Verifying programs

Programs are definitions too: state the spec as a theorem about the function, or put the spec in its type.

Two places for a specification: theorem or type

Extrinsic: write an ordinary function, then prove a theorem about it. Intrinsic: put the property in the type, as in {m : Nat // m + 1 = n} or Vector α n, so every caller gets it for free and must supply the proofs it needs.

details ›

What "sorted" means: ordered and a permutation

programoutput on [3, 1, 2]in order?permutation?fun _ ↦ [][]yesnofun l ↦ l[3, 1, 2]noyes[1, 2, 3]yesyesmergeSort_ok proves both halves for every input list

A correct sort returns a list that is in order and a permutation of its input. Each half alone is met by a wrong program: fun _ => [] is always in order, and fun l => l is always a permutation.

details ›

Termination: structural, well-founded, partial

Every def must terminate, or f n = f n + 1 would prove 0 = 1. Lean accepts recursion on a smaller piece of the input (structural) or along a decreasing measure (termination_by). A partial def runs, but proofs cannot see inside it.

details ›

Semantics and a verified compiler

e = plus (num 2) (num 3)eval e = 5evalsource languagemeaning[push 2, push 3, add]compilestack-machine codestack [5]run, from []samefor every e: run (compile e) [] = [eval e]

A semantics says what a program means; for a small language it can be an interpreter eval. A compiler is correct when running its output gives what eval gives, for every program. CompCert proves this for C.

details ›

Hoare triples and loop invariants (Std.Do)

A Hoare triple says: if holds before runs, then holds after it. A loop needs an invariant, true before every iteration. In Lean, Std.Do writes triples for do programs, and mvcgen turns one into goals.

details ›

State machines and inductive invariants

Model a system as states, an initial state and a step relation. A safety property must hold in every reachable state. Prove it with an inductive invariant: true initially, and preserved by every step from any state where it holds.

details ›

BitVec and bv_decide: machine arithmetic by SAT

you state itverified in LeanSAT solver (CaDiCaL): no solutionexternal, not trustedchecker replays the LRAT certificateproved correct, run compiledtheorem acceptedtrusts kernel + compiler

BitVec n is arithmetic on -bit words, wrapping modulo as hardware does. bv_decide proves such goals by translating them to SAT; an external solver answers, and Lean checks its certificate. A false goal comes back with a counterexample.

details ›

Sources: Lectures 8–10; FPIL

M8 Errors & debugging

Lean's errors are precise: compare the expected and actual types, read the goal, and the fix usually follows.

type mismatch

Type mismatch: e has type A but is expected to have type B. You gave a term of type A; the place needs B. Compare A with B: an argument order, a hidden coercion, or Int versus Nat is often the whole difference.

details ›

unknown identifier / unknown constant

Unknown identifier x or Unknown constant c: no declaration of that name is visible here. The usual causes are a typo, a missing namespace or open, a missing import, or a variable that was never bound.

details ›

unsolved goals and no goals

unsolved goals lists each goal still open when a tactic block ends, with its tag, context and target, at the by, bullet or case … => that opened the block. No goals to be solved: a tactic ran after the proof was done.

details ›

failed to synthesize instance

failed to synthesize instance C T: type-class search found no instance of the class C for the type T. Usually T lacks the structure you assumed, a numeral got the wrong type, or a Decidable instance is missing.

details ›

motive is not type correct

motive is not type correct: rw [h] with h : a = b tried to replace a everywhere, but some other term’s type depends on a, as in v : Fin n. The result would not typecheck. Use subst, simp only [h], or a fact without the dependency.

details ›

Sources: Lectures 3, 5

M9 Formalizing & landmarks

Formalizing means choosing representations and statements you can trust; landmark projects show what that takes at scale.

The formalization recipe

Choose representations, write definitions, test them on small cases, state the theorem, plan a blueprint, search Mathlib, prove with sorry first, audit the axioms. Most mistakes surface in the tests.

details ›

Junk values: 5 - 7 = 0 and x / 0 = 0

Lean’s functions are total, so “undefined” inputs still get a value: in ℕ, 5 - 7 = 0; x / 0 = 0; Real.sqrt (-1) = 0; Real.log 0 = 0. Nothing false follows, because lemmas such as div_self assume a ≠ 0. Your statements must say so too.

details ›

Does the statement say what you mean?

Lean certifies that the proof proves the Lean statement; it cannot check that the statement matches the English claim. Watch for contradictory hypotheses, swapped quantifiers, junk values, and definitions that differ from the paper’s.

details ›

Blueprints and sorry-first development

main theoremlemma Blemma Clemma Dlemma AMathlib lemmaboxes: stated in Lean, proof = sorry✓✓✓✓✓✓#print axioms main: no sorryAx

A blueprint cuts a paper proof into small lemmas, each linked to a Lean name, and draws them as a dependency graph. State every lemma with sorry first, check that the pieces fit, then fill the gaps in any order.

details ›

Representing qubits in Lean

A qubit state can be a function Fin 2 → ℂ, a vector in EuclideanSpace ℂ (Fin 2) or a 2×1 matrix. The numbers are the same, but the norms and lemmas differ: on Fin 2 → ℂ, ‖ψ‖ is , not .

details ›

AI provers and benchmarks

An AI prover proposes Lean proofs and the kernel checks them, so a compiled proof needs no trust in the model. The questions move: who wrote the statement, which benchmark, how many attempts, and who checked it independently.

details ›

Landmark formalizations 2020–2026

Large formalizations since 2020 include the Liquid Tensor Experiment (2022), PFR (2023, in three weeks), Carleson’s theorem (2025) and Fermat’s Last Theorem (2026, produced by AI agents). Each 2023–2026 claim here carries a status tag.

details ›

Reading a "formally verified" claim

Five questions before you believe “formally verified”: Is the Lean statement the claim? Does #print axioms list sorryAx or extra axioms? Which code is trusted beyond the kernel? What does the model assume? Who checked it independently?

details ›

Sources: Lectures 5, 7, 13