Module contents
Lesson 22 of 22Research 110 min

Formal proof: Curry-Howard, proof assistants and AI

Connect natural deduction and typed λ-calculus to proof assistants, trusted kernels, Lean 4, language-model proof search, autoformalization, and learning-guided solvers.

After this lesson you can

  • Implement a simply typed λ-calculus type checker and use it as a proof checker.
  • Explain Curry–Howard and proof normalization as β-reduction.
  • Describe proof assistant architecture, tactics, the small kernel, and the de Bruijn criterion.
  • Critically analyze language-model proving, verifier rewards, search, and benchmark contamination.
  • Identify and mitigate risks of incorrectly autoformalized statements.

Before you start

Motivation: who checks the proof?

In 1976, Appel and Haken proved the four-color theorem using an argument whose central part was a computer check of over a thousand configurations no human reviewed by hand. In 1998, Thomas Hales presented a proof of the Kepler sphere-packing conjecture combining hundreds of pages with massive computations; reviewers said they were “almost certain” it was correct, but not completely. In 2024, an open collaboration established that the fifth busy-beaver number is BB(5)=47 176 870\mathrm{BB}(5) = 47\,176\,870: for each five-state Turing machine that had not halted within that many steps, it had to establish nontermination using arguments of many kinds.

All three stories ended similarly. Georges Gonthier formalized four colors in Coq in 2005 (Gonthier, 2008); the Flyspeck project completed a formal Kepler proof in HOL Light and Isabelle in 2014 (Hales et al., 2017); and BB(5)\mathrm{BB}(5) was announced with a Coq-checked proof (bbchallenge). In each case “is it correct?” became a more manageable question: does a small, public, carefully reviewed program accept this file? The same program handles frontier research: in July 2022 Lean verification was completed for a central theorem by Clausen and Scholze on liquid vector spaces, a challenge Scholze himself had posed a year and a half earlier (Liquid Tensor Experiment).

There is now a fourth source of proofs nobody wants to check by hand: language models. A model easily produces text that looks like a proof and often makes mistakes, sometimes subtle ones. But if it produces a term in a proof assistant’s language, distrust no longer matters: the kernel accepts or rejects it, and in the latter case the model tries again. This pairing of an unreliable generator and reliable verifier underlies AlphaProof and DeepSeek-Prover-V2, and reflects the asymmetry seen in SAT: finding is hard, checking is easy. Logic guarantees this generally. First-order validity is semidecidable but undecidable (Church and Turing), so no algorithm decides whether a formula has a proof (enumerating candidates finds one if it exists, but cannot know when to give up), whereas checking a given proof is a mechanical computation that always terminates.

This lesson builds the idea from the ground up:

  1. A minimal programming language, simply typed λ-calculus, with its type checker.
  2. The Curry–Howard correspondence: that type checker is a proof checker for intuitionistic natural deduction, and executing a program simplifies a proof.
  3. How this scales to a real proof assistant (Lean 4), with its trusted kernel and tactics, and how it performs structural induction.
  4. How to build a language-model prover, which part learns and which must never learn, and what to check before trusting a benchmark figure.

Simply typed λ-calculus

Types, terms, and rules

Fix a set of atomic types A,B,C,…A, B, C, \dots. Types are generated by the grammar

S,T  ::=  A  ∣  ⊥  ∣  S→T  ∣  S∧T  ∣  S∨T,S, T \;::=\; A \;\mid\; \bot \;\mid\; S \to T \;\mid\; S \land T \;\mid\; S \lor T,

and terms, with variables x,y,…x, y, \dots, by

t,u  ::=  x  ∣  λx:S. t  ∣  t u  ∣  ⟨t,u⟩  ∣  π1 t  ∣  π2 t  ∣  inl t  ∣  inr t  ∣  case  t  of  inl x⇒u∣inr y⇒v  ∣  abort t.t, u \;::=\; x \;\mid\; \lambda x{:}S.\, t \;\mid\; t\,u \;\mid\; \langle t, u\rangle \;\mid\; \pi_1\,t \;\mid\; \pi_2\,t \;\mid\; \mathsf{inl}\,t \;\mid\; \mathsf{inr}\,t \;\mid\; \mathsf{case}\;t\;\mathsf{of}\;\mathsf{inl}\,x \Rightarrow u \mid \mathsf{inr}\,y \Rightarrow v \;\mid\; \mathsf{abort}\,t.

Both are inductive definitions, so everything that follows is proved by structural induction. λx:S. t\lambda x{:}S.\,t is the function mapping xx to tt (in Python, lambda x: t with a type annotation), t ut\,u applies tt to uu, ⟨t,u⟩\langle t, u\rangle is a pair and π1,π2\pi_1, \pi_2 its projections; inl\mathsf{inl} and inr\mathsf{inr} tag a value as left or right in a disjoint union and case\mathsf{case} examines it; ⊥\bot is the empty type and abort\mathsf{abort} says that, given a value of empty type, you could make anything. We abbreviate ¬S\lnot S as S→⊥S \to \bot. Application associates left (f x y=(f x) yf\,x\,y = (f\,x)\,y) and the arrow right (A→B→C=A→(B→C)A \to B \to C = A \to (B \to C)), so a two-argument function returns a function.

A context Γ=x1:S1,…,xn:Sn\Gamma = x_1 : S_1, \dots, x_n : S_n assigns types to variables. The judgment Γ⊢t:T\Gamma \vdash t : T (“in context Γ\Gamma, tt has type TT”) has one rule per construction:

(x:S)∈ΓΓ⊢x:S varΓ,x:S⊢t:TΓ⊢λx:S. t:S→T →IΓ⊢t:S→TΓ⊢u:SΓ⊢t u:T →E\dfrac{(x : S) \in \Gamma}{\Gamma \vdash x : S}\,\mathrm{var} \qquad \dfrac{\Gamma, x : S \vdash t : T}{\Gamma \vdash \lambda x{:}S.\,t : S \to T}\,{\to}\mathrm{I} \qquad \dfrac{\Gamma \vdash t : S \to T \quad \Gamma \vdash u : S}{\Gamma \vdash t\,u : T}\,{\to}\mathrm{E} Γ⊢t:SΓ⊢u:TΓ⊢⟨t,u⟩:S∧T ∧IΓ⊢t:S∧TΓ⊢π1 t:S ∧E1Γ⊢t:S∧TΓ⊢π2 t:T ∧E2\dfrac{\Gamma \vdash t : S \quad \Gamma \vdash u : T}{\Gamma \vdash \langle t, u\rangle : S \land T}\,{\land}\mathrm{I} \qquad \dfrac{\Gamma \vdash t : S \land T}{\Gamma \vdash \pi_1\,t : S}\,{\land}\mathrm{E}_1 \qquad \dfrac{\Gamma \vdash t : S \land T}{\Gamma \vdash \pi_2\,t : T}\,{\land}\mathrm{E}_2 Γ⊢t:SΓ⊢inl t:S∨T ∨I1Γ⊢t:S∨TΓ,x:S⊢u:RΓ,y:T⊢v:RΓ⊢case  t  of  inl x⇒u∣inr y⇒v:R ∨EΓ⊢t:⊥Γ⊢abort t:R ⊥E\dfrac{\Gamma \vdash t : S}{\Gamma \vdash \mathsf{inl}\,t : S \lor T}\,{\lor}\mathrm{I}_1 \qquad \dfrac{\Gamma \vdash t : S \lor T \quad \Gamma, x : S \vdash u : R \quad \Gamma, y : T \vdash v : R}{\Gamma \vdash \mathsf{case}\;t\;\mathsf{of}\;\mathsf{inl}\,x \Rightarrow u \mid \mathsf{inr}\,y \Rightarrow v : R}\,{\lor}\mathrm{E} \qquad \dfrac{\Gamma \vdash t : \bot}{\Gamma \vdash \mathsf{abort}\,t : R}\,{\bot}\mathrm{E}

with ∨I2{\lor}\mathrm{I}_2 symmetric to ∨I1{\lor}\mathrm{I}_1. The rule names are no accident, as you will see. To determine the type of inl t\mathsf{inl}\,t and abort t\mathsf{abort}\,t, the implementation annotates the other side of the sum and the target type; the text omits them.

Two examples: λa:A. λb:B. a\lambda a{:}A.\,\lambda b{:}B.\,a has type A→B→AA \to B \to A: it receives an aa, then an bb, and returns the aa. λp:A∧B. ⟨π2 p,π1 p⟩\lambda p{:}A \land B.\,\langle \pi_2\,p, \pi_1\,p\rangle has type A∧B→B∧AA \land B \to B \land A: it swaps a pair. By contrast λx:A. x x\lambda x{:}A.\,x\,x has no type for any AA: to apply xx to anything, xx would have to be a function S→TS \to T, and for the argument to fit, S=S→TS = S \to T, an equation with no solution among finite types. This impossibility is the first hint why well-typed programs always terminate: self-application is the ingredient untyped λ-calculus uses to build infinite loops, such as (λx. x x)(λx. x x)(\lambda x.\,x\,x)(\lambda x.\,x\,x).

β-reduction

Executing a program simplifies its redexes: a constructor immediately followed by its destructor.

(λx:S. t) u  →β  t[x:=u],π1⟨t,u⟩→βt,π2⟨t,u⟩→βu,(\lambda x{:}S.\,t)\,u \;\to_\beta\; t[x := u], \qquad \pi_1\langle t, u\rangle \to_\beta t, \qquad \pi_2\langle t, u\rangle \to_\beta u, case  (inl t)  of  inl x⇒u∣inr y⇒v  →β  u[x:=t],\mathsf{case}\;(\mathsf{inl}\,t)\;\mathsf{of}\;\mathsf{inl}\,x \Rightarrow u \mid \mathsf{inr}\,y \Rightarrow v \;\to_\beta\; u[x := t],

and the symmetric rule for inr\mathsf{inr}. Reduction applies in any subterm. Substitution t[x:=u]t[x := u] replaces free occurrences of xx with uu and renames binders in tt that would capture free variables of uu: exactly the capture-avoiding substitution of predicate logic. A term without redexes is in normal form.

What the type system guarantees

Proof

By structural induction on tt. The rules are syntax-directed: each form of tt matches exactly one rule’s conclusion, whose premises concern immediate subterms. For a variable, the type is assigned by Γ\Gamma (if absent, there is no type). For λx:S. t\lambda x{:}S.\,t, the induction hypothesis gives at most one TT with Γ,x:S⊢t:T\Gamma, x : S \vdash t : T, and the type is S→TS \to T. For t ut\,u, compute the types of tt and uu (unique by hypothesis); a type exists exactly when that of tt has form S→TS \to T with SS equal to that of uu, and then it is TT. The remaining cases are similar; in case\mathsf{case} both branches must have the same type. The recursion is structural, so it terminates.

∎
Proof

The key case is the root redex (λx:S. b) u(\lambda x{:}S.\,b)\,u. By the rules, Γ,x:S⊢b:T\Gamma, x : S \vdash b : T and Γ⊢u:S\Gamma \vdash u : S. The substitution lemma says that then Γ⊢b[x:=u]:T\Gamma \vdash b[x := u] : T, proved by induction on the derivation of bb: replace each xx leaf of that derivation using assumption x:Sx : S by the entire derivation of uu; the other rules are unaffected. Pair and sum redexes are analogous, and reduction inside a subterm is handled by induction on position.

∎

The complete strong proof uses Tait’s reducibility candidates and appears in Sørensen and Urzyczyn’s book in the sources. Weak normalization, existence of some terminating strategy, has a short instructive argument for the →\to fragment. First, why the naive idea fails: counting redexes or measuring size is insufficient, because contracting (λx. ⟨x,x⟩) u(\lambda x.\,\langle x, x\rangle)\,u duplicates uu and its redexes. The first figure shows this: a lemma used twice grows the tree from 18 rules to 20 and from one detour to two.

Proof

(Weak normalization for the →\to fragment, Turing–Prawitz argument.) Call the degree of a redex (λx:S. b) u(\lambda x{:}S.\,b)\,u the size of the function type S→TS \to T. Contraction can create new redexes in only three ways: (i) if bb contains x vx\,v and uu is a λ, u vu\,v appears, of degree ∣S∣<∣S→T∣\abs{S} < \abs{S \to T}; (ii) if bb is a λ and the whole redex was applied, (b[x:=u]) w(b[x:=u])\,w has degree ∣T∣<∣S→T∣\abs{T} < \abs{S \to T}; (iii) if b=xb = x and uu is a λ later applied, likewise with degree ∣S∣\abs{S}. Other redexes of b[x:=u]b[x := u] were already in bb or are copies of those in uu. Let dd be the maximum degree of redexes of tt and nn the count of degree dd. Choose one of degree dd containing no other of degree dd in its argument uu (one exists: among degree dd redexes, take the one starting rightmost in the term). On contraction it disappears, new ones have degree below dd, and copies of uu contain none of degree dd. The pair (d,n)(d, n) decreases in lexicographic order, which is well-founded, so the process terminates.

∎

Together, the three theorems say typing is decidable, types are execution invariants, and every well-typed program terminates. The price of the third property is that the language is not Turing complete. It cannot be: if a total language expressed an interpreter for itself, diagonalization of the halting problem would construct a nonterminating program. Soon you will see why this limitation is a virtue in a proof language.

Curry–Howard: propositions as types

Look again at the typing rules and cover the terms: Γ⊢T\Gamma \vdash T remains, and each rule is exactly a natural-deduction rule from lesson 4. →I{\to}\mathrm{I} introduces implication (assume SS, derive TT, discharge), →E{\to}\mathrm{E} is modus ponens, ∧I{\land}\mathrm{I} and ∧Ei{\land}\mathrm{E}_i concern conjunction, ∨E{\lor}\mathrm{E} is reasoning by cases, and ⊥E{\bot}\mathrm{E} is ex falso. Terms are a linear notation for derivation trees.

Logic (natural deduction)Programming (typed λ-calculus)
proposition SStype SS
proof of SSterm (program) of type SS
open assumption [S]x[S]^xfree variable x:Sx : S
discharge assumption xx (→Ix{\to}\mathrm{I}^x)bind xx with λx\lambda x
modus ponens (→E{\to}\mathrm{E})function application
S∧TS \land Tpair: product type
S∨TS \lor T, proof by casesdisjoint union, case\mathsf{case}
⊥\bot, ex falsoempty type, abort\mathsf{abort}
¬S\lnot Sfunction S→⊥S \to \bot
eliminate a detourone β-reduction step
normal proofprogram in normal form
check a proofcheck the type
Proof

Erasing terms from a derivation of Γ⊢t:T\Gamma \vdash t : T gives a logical derivation: each typing rule becomes the logical rule of the same name, and a variable bound by λx\lambda x marks an assumption discharged with label xx. Conversely, given a logical derivation with labeled assumptions, construct the term by induction on the derivation: an assumption labeled xx is variable xx, an →Ix{\to}\mathrm{I}^x is λx\lambda x applied to the premise’s term, and likewise for each rule. Structural induction shows the constructions are inverses. The last claim is checked case by case in the next section.

∎

Haskell Curry observed the Curry–Howard correspondence for combinatory logic in the 1930s; William Howard formulated it for natural deduction in 1969. Wadler’s article in the sources recounts the history. Its slogan is “propositions as types, proofs as programs.” The practical consequence is enormous: a type checker suffices to check a proof, and type checkers are small programs we know how to write well.

InteractiveThe Curry–Howard mirror
Statement (type)(A→B)→(B→C)→A→C(A \to B) \to (B \to C) \to A \to C
Natural deductionclick a hole to select it
→Ia{\to}\mathrm{I}^{a}
A→CA \to C
→Ig{\to}\mathrm{I}^{g}
(B→C)→A→C(B \to C) \to A \to C
→If{\to}\mathrm{I}^{f}
(A→B)→(B→C)→A→C(A \to B) \to (B \to C) \to A \to C
λ-términothe same object, written inline
λf:A → B. λg:B → C. λa:A.
type: (A→B)→(B→C)→A→C(A \to B) \to (B \to C) \to A \to C
Rules for hole ?:C?: C
Mode
Open holes1
Rules used3
Selected holef:A→B, g:B→C, a:A⊢ ? : Cf : A \to B,\ g : B \to C,\ a : A \vdash\ ?\,:\,C
Still provable? (G4ip)yes, all holes
On the left is a natural-deduction tree; on the right the λ-term that is the same proof. In ‘Build’, click a hole (??) and choose a rule: both sides update together. Hover over a subtree to highlight its subterm, and vice versa. The ‘still provable?’ indicator decides the hole with an exact algorithm: for Peirce's law it always says ‘no’. In ‘Normalize’, each β-step removes a detour (red) from the tree: watch the lemma used twice grow the tree before it shrinks.

Build composition in the figure: with assumptions f:A→Bf : A \to B, g:B→Cg : B \to C and a:Aa : A already introduced, the hole asks for CC. The only rule concluding CC applies gg, leaving a hole of type BB; the only one concluding BB applies ff, leaving one of type AA, and aa closes it. The resulting term λf. λg. λa. g (f a)\lambda f.\,\lambda g.\,\lambda a.\,g\,(f\,a) is function composition and the tree is hypothetical syllogism. They are not merely similar: they are the same thing written in two ways.

Detours and proof normalization

A detour in a derivation is an introduction immediately followed by elimination of the same connective: prove S→TS \to T by assuming SS and immediately use it with modus ponens, or prove S∧TS \land T only to retain SS. Dag Prawitz proved in 1965 that every detour can be eliminated, and his procedure is β-reduction rule by rule:

[S]x⋮TS→T →Ix⋮ST →E⇝⋮S⋮T(λx:S. t) u→βt[x:=u].\dfrac{\dfrac{\begin{matrix}[S]^x \\ \vdots \\ T\end{matrix}}{S \to T}\,{\to}\mathrm{I}^x \qquad \begin{matrix}\vdots \\ S\end{matrix}}{T}\,{\to}\mathrm{E} \quad\leadsto\quad \begin{matrix}\vdots \\ S \\ \vdots \\ T\end{matrix} \qquad\qquad (\lambda x{:}S.\,t)\,u \to_\beta t[x := u].

On the left, instead of assuming SS and discharging it, paste the proof of SS at every [S]x[S]^x leaf; on the right, substitute uu by xx. For conjunction, π1⟨t,u⟩→t\pi_1\langle t, u\rangle \to t discards the unused half’s proof; for disjunction, case (inl t)\mathsf{case}\,(\mathsf{inl}\,t) chooses the appropriate branch. A detour is literally a lemma: prove a general intermediate result and apply it to a case. Normalizing replaces each use of the lemma with a specialized copy of its proof, called inlining in programming. Thus normalization can grow a proof enormously: worst-case growth is not bounded by any fixed tower of exponentials.

Consistency and what cannot be proved

Normalization has immediate logical consequences. A term is neutral if it is a variable or an elimination (t ut\,u, πi t\pi_i\,t, case t…\mathsf{case}\,t \ldots, abort t\mathsf{abort}\,t) whose principal argument tt is neutral. By structural induction every typed normal term is either an introduction (λ\lambda, pair, inl\mathsf{inl}, inr\mathsf{inr}) or neutral: if it is an elimination, its principal argument cannot be an introduction (there would be a redex), so is neutral. A neutral term has a free variable at its head, the variable at the bottom of its elimination chain.

Proof

If ⊢t:⊥\vdash t : \bot, normalization and preservation give a normal, closed t′t' with ⊢t′:⊥\vdash t' : \bot. Being closed it is not neutral, so is an introduction. But no introduction has type ⊥\bot: ⊥\bot has no introduction rule.

∎

The same argument gives finer negative results without semantics:

Proof

Excluded middle. A closed normal term of type A∨¬AA \lor \lnot A is an introduction: inl s\mathsf{inl}\,s with ⊢s:A\vdash s : A closed and normal, impossible because ss would be an introduction and atoms have none; or inr s\mathsf{inr}\,s with ⊢s:A→⊥\vdash s : A \to \bot. Then s=λa:A. rs = \lambda a{:}A.\,r with a:A⊢r:⊥a : A \vdash r : \bot normal. rr is not an introduction (there are none for ⊥\bot), so is neutral with head aa. But no elimination applies to a:Aa : A (it is not a function, pair, sum, or ⊥\bot), so r=ar = a, of type A≠⊥A \neq \bot. Contradiction.

Peirce. A closed normal term is λf:(A→B)→A. r\lambda f{:}(A \to B) \to A.\,r with f⊢r:Af \vdash r : A. rr is neutral with head ff (the only variable), and the only elimination possible on ff is application: r=f ur = f\,u, already of type AA and allowing no more eliminations. Then f⊢u:A→Bf \vdash u : A \to B is normal. If uu were neutral, its head would be ff and its type AA, not A→BA \to B; so u=λa:A. r′u = \lambda a{:}A.\,r' with f,a⊢r′:Bf, a \vdash r' : B. r′r' is neutral, with head aa (type AA, allowing no elimination) or ff (type AA after application). Neither gives BB.

∎

Both formulas are classical tautologies: what fails is that an intuitionistic proof of A∨¬AA \lor \lnot A must decide which side holds, and without knowing anything about AA there is no way. By contrast there is a term for ¬¬(A∨¬A)\lnot\lnot(A \lor \lnot A):

λk:¬(A∨¬A).  k (inr (λa:A.  k (inl a))).\lambda k{:}\lnot(A \lor \lnot A).\;k\,\big(\mathsf{inr}\,(\lambda a{:}A.\;k\,(\mathsf{inl}\,a))\big).

Read it as a program with a clever strategy: kk promises to refute any proof of A∨¬AA \lor \lnot A. The term first supplies “¬A\lnot A,” as a function that, if it ever receives an a:Aa : A, goes back and gives kk the proof inl a\mathsf{inl}\,a. Glivenko proved in 1929 that this is general in propositional logic: φ\varphi is a classical tautology if and only if ¬¬φ\lnot\lnot\varphi is intuitionistically provable. The laboratory’s table illustrates this.

Classical logic: add an axiom

Classical logic is recovered by adding an axiom, a constant without a definition: em:A∨¬A\mathsf{em} : A \lor \lnot A in the context. With it, Peirce has an inhabitant:

em:A∨¬A  ⊢  λf.  case  em  of  inl a⇒a∣inr n⇒f (λa. abort (n a))  :  ((A→B)→A)→A.\mathsf{em} : A \lor \lnot A \;\vdash\; \lambda f.\;\mathsf{case}\;\mathsf{em}\;\mathsf{of}\;\mathsf{inl}\,a \Rightarrow a \mid \mathsf{inr}\,n \Rightarrow f\,(\lambda a.\,\mathsf{abort}\,(n\,a)) \;:\; ((A \to B) \to A) \to A.

An axiom has no computational content: a term using it gets stuck at case  em\mathsf{case}\;\mathsf{em}, because em\mathsf{em} is neither inl\mathsf{inl} nor inr\mathsf{inr}. Griffin discovered another route in 1990: Scheme’s control operator call/cc, which captures the program’s continuation, has exactly the type of Peirce’s law. Classical logic corresponds to programs with jumps. Lean 4 incorporates classical logic as an axiom, Classical.choice, from which excluded middle follows (Diaconescu’s theorem); you will see it when printing the axioms of a mathlib theorem.

Implementation from scratch: a proof checker

The checker fits in one function. Types are strings (atoms and 'bot') or tuples ('->', S, T), ('*', S, T) and ('+', S, T); terms are tagged tuples. This first version covers →\to, ∧\land and ⊥\bot.

[ ]Types, terms, and checkerBrowser
# Tipos: 'A', 'B'... (átomos), 'bot', ('->', S, T), ('*', S, T), ('+', S, T)
# Términos: ('var', x), ('lam', x, T, cuerpo), ('app', t, u), ('pair', t, u), ('fst', t), ('snd', t),
#           ('inl', t, B), ('inr', A, t), ('case', t, x, u, y, v), ('abort', t, T)

def arr(a, b): return ('->', a, b)
def neg(a): return ('->', a, 'bot')

def show(t, p=0):
    """Tipo en notación lógica, con los paréntesis mínimos."""
    if isinstance(t, str):
        return '⊥' if t == 'bot' else t
    op, a, b = t
    if op == '->' and b == 'bot':
        return '¬' + show(a, 4)
    lvl, sym, pa, pb = {'->': (1, '→', 2, 1), '+': (2, '∨', 3, 2), '*': (3, '∧', 4, 3)}[op]
    s = f"{show(a, pa)} {sym} {show(b, pb)}"
    return f"({s})" if p > lvl else s

def typecheck(term, ctx):
    """Tipo de term en el contexto ctx (dict nombre -> tipo). Lanza TypeError si está mal tipado."""
    tag = term[0]
    if tag == 'var':
        if term[1] not in ctx:
            raise TypeError(f"variable sin ligar: {term[1]}")
        return ctx[term[1]]
    if tag == 'lam':
        _, x, T, body = term
        return ('->', T, typecheck(body, {**ctx, x: T}))
    if tag == 'app':
        f, a = typecheck(term[1], ctx), typecheck(term[2], ctx)
        if not (isinstance(f, tuple) and f[0] == '->'):
            raise TypeError(f"se aplica algo de tipo {show(f)}, que no es una función")
        if f[1] != a:
            raise TypeError(f"argumento de tipo {show(a)}, se esperaba {show(f[1])}")
        return f[2]
    if tag == 'pair':
        return ('*', typecheck(term[1], ctx), typecheck(term[2], ctx))
    if tag in ('fst', 'snd'):
        p = typecheck(term[1], ctx)
        if not (isinstance(p, tuple) and p[0] == '*'):
            raise TypeError(f"proyección de algo de tipo {show(p)}")
        return p[1] if tag == 'fst' else p[2]
    if tag == 'abort':
        if typecheck(term[1], ctx) != 'bot':
            raise TypeError("abort necesita una prueba de ⊥")
        return term[2]
    raise TypeError(f"construcción desconocida: {tag}")   # inl, inr y case: en el ejercicio

V = lambda x: ('var', x)
A, B, C = 'A', 'B', 'C'

pruebas = {
    "K": ('lam', 'a', A, ('lam', 'b', B, V('a'))),
    "S": ('lam', 'f', arr(A, arr(B, C)), ('lam', 'g', arr(A, B), ('lam', 'x', A,
          ('app', ('app', V('f'), V('x')), ('app', V('g'), V('x')))))),
    "contrarrecíproco": ('lam', 'f', arr(A, B), ('lam', 'nb', neg(B), ('lam', 'a', A,
          ('app', V('nb'), ('app', V('f'), V('a')))))),
    "∧ conmutativa": ('lam', 'p', ('*', A, B), ('pair', ('snd', V('p')), ('fst', V('p')))),
    "ex falso": ('lam', 'z', 'bot', ('abort', V('z'), A)),
}
for nombre, t in pruebas.items():
    print(f"{nombre:18s} ⊢ {show(typecheck(t, {}))}")

malas = {
    "argumento equivocado": ('lam', 'f', arr(A, B), ('lam', 'b', B, ('app', V('f'), V('b')))),
    "variable libre": ('lam', 'a', A, V('c')),
    "aplicar un átomo": ('lam', 'a', A, ('app', V('a'), V('a'))),
}
for nombre, t in malas.items():
    try:
        typecheck(t, {})
    except TypeError as e:
        print(f"{nombre:22s} rechazado: {e}")

The first five lines are checked theorems; the last three are rejected “proofs.” The second, λa. c\lambda a.\,c, cites a nonexistent assumption, and the third, λa. a a\lambda a.\,a\,a, is the self-application forbidden by the type system. Disjunction remains (inl\mathsf{inl}, inr\mathsf{inr}, case\mathsf{case}). You will write it in the coding exercise; here a hidden cell loads it so the rest of the laboratory works.

Now reduction: capture-avoiding substitution, one normal-order step (the leftmost outermost redex), and a loop checking at every step that the type is unchanged, turning preservation into assert.

[ ]β-reduction and normalizationBrowser
import itertools

HIJOS = {'var': (), 'lam': (3,), 'app': (1, 2), 'pair': (1, 2), 'fst': (1,), 'snd': (1,), 'inl': (1,),
         'inr': (2,), 'abort': (1,), 'case': (1, 3, 5)}

def libres(t):
    tag = t[0]
    if tag == 'var':
        return {t[1]}
    if tag == 'lam':
        return libres(t[3]) - {t[1]}
    if tag == 'case':
        return libres(t[1]) | (libres(t[3]) - {t[2]}) | (libres(t[5]) - {t[4]})
    return set().union(*(libres(t[i]) for i in HIJOS[tag]))

_fresco = itertools.count()

def sust(t, x, s):
    """t[x := s] sin captura: si una ligadura capturaría una variable libre de s, se renombra."""
    tag = t[0]
    if tag == 'var':
        return s if t[1] == x else t
    def ligadura(y, cuerpo):
        if y == x:
            return y, cuerpo
        if y in libres(s):
            z = f"{y}{next(_fresco)}"
            cuerpo, y = sust(cuerpo, y, ('var', z)), z
        return y, sust(cuerpo, x, s)
    if tag == 'lam':
        y, cuerpo = ligadura(t[1], t[3])
        return ('lam', y, t[2], cuerpo)
    if tag == 'case':
        y1, u = ligadura(t[2], t[3])
        y2, v = ligadura(t[4], t[5])
        return ('case', sust(t[1], x, s), y1, u, y2, v)
    return tuple(sust(c, x, s) if i in HIJOS[tag] else c for i, c in enumerate(t))

def es_desvio(t):
    return ((t[0] == 'app' and t[1][0] == 'lam') or (t[0] in ('fst', 'snd') and t[1][0] == 'pair')
            or (t[0] == 'case' and t[1][0] in ('inl', 'inr')))

def contraer(t):
    if t[0] == 'app':                                  # (λx. b) a  →  b[x := a]
        return sust(t[1][3], t[1][1], t[2])
    if t[0] == 'fst':                                  # π₁⟨a, b⟩  →  a
        return t[1][1]
    if t[0] == 'snd':
        return t[1][2]
    _, e, x, u, y, v = t                               # case (inl a) ...  →  u[x := a]
    return sust(u, x, e[1]) if e[0] == 'inl' else sust(v, y, e[2])

def paso(t):
    """Un paso en orden normal, o None si t ya es normal."""
    if es_desvio(t):
        return contraer(t)
    for i in HIJOS[t[0]]:
        r = paso(t[i])
        if r is not None:
            return t[:i] + (r,) + t[i + 1:]
    return None

tam = lambda t: 1 + sum(tam(t[i]) for i in HIJOS[t[0]])
desvios = lambda t: es_desvio(t) + sum(desvios(t[i]) for i in HIJOS[t[0]])

def pp(t):
    """Término en notación habitual (sin las anotaciones de inl, inr y abort)."""
    tag = t[0]
    atom = lambda u: pp(u) if u[0] in ('var', 'pair') else f"({pp(u)})"
    if tag == 'var':
        return t[1]
    if tag == 'lam':
        return f"λ{t[1]}:{show(t[2])}. {pp(t[3])}"
    if tag == 'app':
        return f"{pp(t[1]) if t[1][0] in ('var', 'app') else atom(t[1])} {atom(t[2])}"
    if tag == 'pair':
        return f"⟨{pp(t[1])}, {pp(t[2])}⟩"
    if tag in ('fst', 'snd'):
        return f"{'π₁' if tag == 'fst' else 'π₂'} {atom(t[1])}"
    if tag in ('inl', 'inr', 'abort'):
        return f"{tag} {atom(t[1] if tag != 'inr' else t[2])}"
    return f"case {pp(t[1])} of inl {t[2]} ⇒ {pp(t[3])} | inr {t[4]} ⇒ {pp(t[5])}"

def normalizar(t, traza=True):
    tipo = typecheck(t, {})
    pasos = 0
    while True:
        if traza:
            print(f"  paso {pasos}: tamaño {tam(t):3d}, desvíos {desvios(t)}")
        r = paso(t)
        if r is None:
            return t, pasos
        t, pasos = r, pasos + 1
        assert typecheck(t, {}) == tipo, "la reducción ha cambiado el tipo"

# un lema A → C demostrado una vez y usado dos veces (la figura, modo «Normalizar»)
lema = ('lam', 'x', A, ('app', V('g'), ('app', V('f'), V('x'))))
uso = ('lam', 'h', arr(A, C), ('pair', ('app', V('h'), V('a')), ('app', V('h'), V('a'))))
prueba = ('lam', 'f', arr(A, B), ('lam', 'g', arr(B, C), ('lam', 'a', A, ('app', uso, lema))))
print("⊢", show(typecheck(prueba, {})))
normal, n = normalizar(prueba)
print("forma normal:", pp(normal))

# el combinador S aplicado a K dos veces: S K K se reduce a la identidad
K = lambda T, U: ('lam', 'a', T, ('lam', 'b', U, V('a')))
S = lambda T, U, W: ('lam', 'f', arr(T, arr(U, W)), ('lam', 'g', arr(T, U), ('lam', 'x', T,
                     ('app', ('app', V('f'), V('x')), ('app', V('g'), V('x'))))))
SKK = ('app', ('app', S(A, arr(A, A), A), K(A, arr(A, A))), K(A, A))
print("\nS K K ⊢", show(typecheck(SKK, {})))
nf, n = normalizar(SKK, traza=False)
print(f"forma normal tras {n} pasos: {pp(nf)}")

The lemma trace reproduces the figure: sizes 18, 20, 17 and 14, with 1, 2, 1 and 0 detours. The number of detours rises before falling, so normalization needs a finer measure than counting them. S K KS\,K\,K is identity: in logic, a derivation of A→AA \to A detouring through two Hilbert axioms; in programming, a program returning its argument after four steps.

Finally, what is provable? Intuitionistic propositional logic is decidable, and there is no need for blind term search: Dyckhoff’s G4ip sequent calculus (1992) has no contraction and its rules always decrease a sequent measure, so proof search terminates; it is sound and complete for this logic. Compare it with classical truth (truth tables) and, for failing formulas, supply a Kripke model: an ordered set of worlds where truth persists into later worlds and S→TS \to T holds in ww if in every world after ww where SS holds, TT holds too. Intuitionistic logic is sound and complete for these models, as classical logic is for valuations.

[ ]What is provable: G4ip and a Kripke countermodelBrowser
from functools import lru_cache
from itertools import product

@lru_cache(maxsize=None)
def g4ip(gamma, goal):
    """¿Γ ⊢ goal en lógica proposicional intuicionista? gamma es un frozenset de tipos."""
    quitar = lambda h: gamma - {h}
    for h in gamma:                                    # reglas invertibles a la izquierda
        if h == 'bot':
            return True
        if isinstance(h, tuple):
            op, a, b = h
            if op == '*':
                return g4ip(quitar(h) | {a, b}, goal)
            if op == '+':
                return g4ip(quitar(h) | {a}, goal) and g4ip(quitar(h) | {b}, goal)
            if op == '->':
                if isinstance(a, str) and a != 'bot' and a in gamma:
                    return g4ip(quitar(h) | {b}, goal)
                if a == 'bot':
                    return g4ip(quitar(h), goal)
                if isinstance(a, tuple) and a[0] == '*':
                    return g4ip(quitar(h) | {arr(a[1], arr(a[2], b))}, goal)
                if isinstance(a, tuple) and a[0] == '+':
                    return g4ip(quitar(h) | {arr(a[1], b), arr(a[2], b)}, goal)
    if isinstance(goal, str) and goal in gamma:
        return True
    if isinstance(goal, tuple) and goal[0] == '->':    # reglas invertibles a la derecha
        return g4ip(gamma | {goal[1]}, goal[2])
    if isinstance(goal, tuple) and goal[0] == '*':
        return g4ip(gamma, goal[1]) and g4ip(gamma, goal[2])
    # reglas no invertibles: elegir un lado de ∨, o usar una hipótesis (C → D) → B
    if isinstance(goal, tuple) and goal[0] == '+' and (g4ip(gamma, goal[1]) or g4ip(gamma, goal[2])):
        return True
    for h in gamma:
        if isinstance(h, tuple) and h[0] == '->' and isinstance(h[1], tuple) and h[1][0] == '->':
            (_, c, d), b = h[1], h[2]
            if g4ip(quitar(h) | {arr(d, b)}, h[1]) and g4ip(quitar(h) | {b}, goal):
                return True
    return False

def tautologia(phi, atomos=('A', 'B')):
    def val(t, v):
        if t == 'bot':
            return False
        if isinstance(t, str):
            return v[t]
        op, a, b = t
        return {'->': (not val(a, v)) or val(b, v), '*': val(a, v) and val(b, v), '+': val(a, v) or val(b, v)}[op]
    return all(val(phi, dict(zip(atomos, bits))) for bits in product([False, True], repeat=len(atomos)))

lem = ('+', A, neg(A))
peirce = arr(arr(arr(A, B), A), A)
formulas = {
    "tercero excluido": lem,
    "¬¬ del tercero excluido": neg(neg(lem)),
    "ley de Peirce": peirce,
    "contrarrecíproco": arr(arr(A, B), arr(neg(B), neg(A))),
    "recíproco del contrarrecíproco": arr(arr(neg(B), neg(A)), arr(A, B)),
    "eliminar ¬¬": arr(neg(neg(A)), A),
    "triple negación": arr(neg(neg(neg(A))), neg(A)),
    "De Morgan (una dirección)": arr(neg(('+', A, B)), ('*', neg(A), neg(B))),
    "De Morgan (la otra)": arr(neg(('*', A, B)), ('+', neg(A), neg(B))),
}
print(f"{'':32s} {'clásica':>8s} {'intuicionista':>14s}")
for nombre, phi in formulas.items():
    print(f"{nombre:32s} {str(tautologia(phi)):>8s} {str(g4ip(frozenset(), phi)):>14s}    {show(phi)}")

# Contramodelo de Kripke: dos mundos w0 ≤ w1; A solo es verdad en w1 y B en ninguno
sucesores, verdad = {0: [0, 1], 1: [1]}, {'A': {1}, 'B': set()}

def fuerza(w, t):
    """w ⊩ t: la implicación (y por tanto ¬) mira todos los mundos accesibles desde w."""
    if t == 'bot':
        return False
    if isinstance(t, str):
        return w in verdad[t]
    op, a, b = t
    if op == '*':
        return fuerza(w, a) and fuerza(w, b)
    if op == '+':
        return fuerza(w, a) or fuerza(w, b)
    return all((not fuerza(v, a)) or fuerza(v, b) for v in sucesores[w])

print("\nEn el mundo w0 del modelo de dos mundos:")
for nombre in ["tercero excluido", "ley de Peirce", "eliminar ¬¬", "¬¬ del tercero excluido"]:
    print(f"  w0 ⊩ {nombre:26s} {fuerza(0, formulas[nombre])}")

# con el tercero excluido como axioma en el contexto, Peirce sí tiene habitante
peirce_clasica = ('lam', 'f', arr(arr(A, B), A),
                  ('case', V('em'), 'a', V('a'),
                   'n', ('app', V('f'), ('lam', 'a', A, ('abort', ('app', V('n'), V('a')), B)))))
print("\nem : A ∨ ¬A ⊢", show(typecheck(peirce_clasica, {'em': lem})))
nnlem = ('lam', 'k', neg(lem), ('app', V('k'), ('inr', A, ('lam', 'a', A, ('app', V('k'), ('inl', V('a'), neg(A)))))))
print("⊢", show(typecheck(nnlem, {})), "   sin axiomas")

The table confirms this section’s theorem and Glivenko’s: every formula is a classical tautology, four are intuitionistic and five are not. The two-world model explains excluded middle’s failure: in w0w_0, AA is not yet true, but neither is ¬A\lnot A, because in the next world AA will be true. This is Kripke’s reading of “we do not know yet.” In the same world w0w_0, by contrast, ¬¬(A∨¬A)\lnot\lnot(A \lor \lnot A) holds, as required.

Proof assistants

From λ-calculus to Lean: dependent types

Simply typed λ-calculus corresponds to propositional logic. Mathematics needs quantifiers, and Curry–Howard’s extension to predicate logic uses dependent types, types depending on values. A proof of ∀n∈N, P(n)\forall n \in \N,\, P(n) is a function that for each nn returns a proof of P(n)P(n): its type Πn:NP(n)\Pi_{n : \N} P(n) is a function type whose result type depends on the argument. A proof of ∃n, P(n)\exists n,\, P(n) is a pair: a witness nn and a proof of P(n)P(n), of type Σn:NP(n)\Sigma_{n : \N} P(n). Propositions are types in a special universe Prop, and a proposition is true when inhabited.

Lean 4 and Rocq (called Coq until 2025) use variants of the calculus of inductive constructions: λ-calculus with dependent types, universes, and inductive definitions. Isabelle/HOL follows Robin Milner’s LCF tradition: theorems are values of an abstract type thm constructible only by a few kernel functions, each an inference rule of higher-order logic. Both architectures share the central idea.

The de Bruijn criterion requires correctness to depend only on the kernel: a buggy tactic can fail or produce a malformed term, but the kernel rejects it; it cannot make the kernel accept a falsehood. This leaves the large changing part of the system, written by thousands and now also language models, outside the trusted base. Lean goes further: a term accepted by its kernel can be exported and rechecked by independently written checkers.

Architecture: elaborator, tactics, and kernel

A Lean theorem can be written directly as a term or with a tactic script:

theorem contra (p q : Prop) : (p → q) → ¬q → ¬p :=
  fun hpq hnq hp => hnq (hpq hp)           -- el λ-término de la sección anterior

theorem contra' (p q : Prop) : (p → q) → ¬q → ¬p := by
  intro hpq hnq hp                          -- tres →I
  exact hnq (hpq hp)                        -- →E dos veces

Both versions produce the same term: block by executes tactics filling a term with holes (metavariables, written ?_ by Lean) until none remain, and the final term reaches the kernel. A tactic is thus a program transforming one state (a list of goals of the form “assumptions ⊢\vdash goal”) into another while leaving a piece of term. intro is →I{\to}\mathrm{I}, apply h is →E{\to}\mathrm{E} read backward (to prove TT with h:S→Th : S \to T, suffice to prove SS), exact closes with a term, cases is ∨E{\lor}\mathrm{E}. Powerful tactics (simp, omega, ring, linarith, decide) are decision or rewriting procedures producing huge proof terms no one reads but the kernel still checks.

Lean’s mathematics library mathlib contains over a hundred thousand theorems, from linear algebra to measure theory, written by a large community. For an automated prover it is both the environment (working definitions and lemmas) and training data.

What is in the trusted base

Kernel acceptance means exactly this: the written statement, with the written definitions, follows from the system’s axioms. The trusted computing base includes everything that must be correct for that to imply what you intended:

  1. The kernel, and the hardware and compiler running it. It is small, carefully reviewed, and checkable with independent implementations.
  2. Axioms. Lean has three: propositional extensionality (propext), quotient (Quot.sound), and choice (Classical.choice). Command #print axioms t lists those used by the proof of t. Any other is a warning: sorryAx means an sorry (a manually filled hole) somewhere in the lemma chain, and Lean.ofReduceBool means native_decide was used, trusting the compiler as well as the kernel.
  3. The statement and definitions. The kernel does not know what you meant. If “prime” is defined incorrectly or the statement does not say what you think, the proof correctly proves something else. Automation does not remove this issue; it returns in autoformalization.

Structural induction in an assistant

In Lean, naturals and lists are inductive types, defined by constructors exactly as in lesson 7:

inductive Nat where
  | zero : Nat
  | succ (n : Nat) : Nat

inductive List (α : Type) where
  | nil : List α
  | cons (head : α) (tail : List α) : List α

Each declaration automatically generates a recursor, the constant expressing structural recursion and induction. The one for Nat has type (simplified):

Nat.rec:ΠM:N→Sort u  M(0)→(Πn:N  M(n)→M(n+1))→Πt:N  M(t).\mathsf{Nat.rec} : \Pi_{M : \N \to \mathsf{Sort}\,u}\; M(0) \to \big(\Pi_{n : \N}\; M(n) \to M(n + 1)\big) \to \Pi_{t : \N}\; M(t).

If MM takes values in Prop, it is the induction principle: from a proof of M(0)M(0) and a function turning proofs of M(n)M(n) into proofs of M(n+1)M(n + 1) comes a proof of M(t)M(t) for every tt. If MM takes values in Type, it is primitive recursion used to define functions. It is the same object: by Curry–Howard, an induction proof is a recursive function. Tactic induction n simply applies Nat.rec with the appropriate motive MM and leaves two holes, one per constructor, with the induction hypothesis in the second. Recursion is structural and therefore terminates, making the proof a proof.

This is why Lean requires every recursive function to terminate. If one could define def bucle : False := bucle, type False would have an inhabitant and logic would be inconsistent: termination of computation and consistency of logic are the same property. Since halting is undecidable, the termination checker is necessarily incomplete: it accepts structural recursion and recursion justified by a well-founded measure, but rejects other functions that do terminate. Functions declared partial can execute, but the kernel cannot unfold them in proofs.

InteractiveTactic-state explorer
theorem rev_rev (l : List α) : rev (rev l) = l := by
Proof state1 goal
goal 1current
h : α
t : List α
ih : rev (rev t) = t
⊢rev (rev t ++ [h]) = h :: t
State after induction l, rfl in the nil case, and simp only [rev] in the cons case. Try rw [ih]: why does it not match? Undo to see earlier steps.
Scriptwhat you would write in Lean
induction l with
| nil =>
rfl
| cons h t ih =>
simp only [rev]
-- open goal
Proof term?_ = hole, ⋯ = hidden
List.rec (motive := fun l => rev (rev l) = l)
  rfl
  (fun h t ih => Eq.mpr ⋯ ?_)
  l
Tactics
Open goals1
Tactics applied3
#print axiomsno sorryAx
Auxiliary lemmapending
A Lean-like goals panel, with the script you would write and the proof term being generated (?_?\_ is a hole). Start where the proof of rev (rev l) = l gets stuck: try rw [ih] and read why it does not match. Then select ‘Auxiliary lemma’, prove it, and return. Inspect the term: induction is an application of List.rec. Try sorry too and observe the #print axioms reading.

The figure’s example is classic. With rev defined by rev [] = [] and rev (a :: as) = rev as ++ [a], induction on l for rev (rev l) = l reaches, in case h :: t, goal rev (rev t ++ [h]) = h :: t with hypothesis ih : rev (rev t) = t. The hypothesis does not apply directly: the goal contains not rev (rev t) but rev applied to something ending in [h]. A lemma is needed saying how rev acts on such lists, rev (l ++ [a]) = a :: rev l, proved separately by induction. This pattern, where the desired property is not inductive and must be strengthened or generalized, is the same as strengthened induction and loop invariants, and is a frequent failure point for automated provers.

def rev {α : Type} : List α → List α
  | [] => []
  | a :: as => rev as ++ [a]

theorem rev_append_single {α : Type} (l : List α) (a : α) :
    rev (l ++ [a]) = a :: rev l := by
  induction l with
  | nil => rfl
  | cons h t ih => simp [rev, ih]

theorem rev_rev {α : Type} (l : List α) : rev (rev l) = l := by
  induction l with
  | nil => rfl
  | cons h t ih => simp [rev, rev_append_single, ih]

Automated proving with language models

From outside, a proof assistant is an environment. A state is the list of open goals; an action is a tactic; the assistant computes the transition, executing the tactic and returning a new state or error; the episode ends in success when no goals remain. It is a deterministic decision process with an infinite action space (any text is a candidate tactic) and sparse binary reward.

The two pieces have opposite roles. The model is a policy π(taˊctica∣estado)\pi(\text{táctica} \given \text{estado}): it provides intuition, often errs, and need not be trusted. The verifier is exact: an inapplicable tactic is not applied, and a kernel-accepted proof is correct regardless of who wrote it. Search converts compute budget into success probability.

InteractiveProof search with a policy and verifier
Theorem¬¬(A∨¬A)\lnot \lnot (A \lor \lnot A) (double negation of excluded middle)
explored state on the frontier rejected tactic duplicate state proof
Node selectedπ = 0.661 · log p = -5.75
tactic apply h2
no goals: proof complete
Success rate11 theorems × 16 seeds
  • q = 0 (random policy)
  • q = 0.60 (yours)
  • q = 1 (near oracle)
As in AlphaZero: policy ↔ policy network · verifier ↔ game rules · closed proof ↔ victory · calls ↔ simulations
0.60
80
seed 2
call 34 of 34
Verifier calls34 / 80
Rejected by verifier22
Duplicate states discarded3
Distinct states explored10
Proof found at call34
Script found (7 tactics)intro; apply h1; right; intro; apply h1; left; apply h2
Best-first search always tries the tactic with greatest accumulated log probability from the root; each attempt calls the verifier, which rejects invalid tactics (crosses) and discards repeated states. The policy is simulated: qq mixes an oracle knowing which tactics leave provable goals (computed by exact G4ip) with noise. Replay search and click nodes. Lower qq: how much budget compensates for a worse policy? Choose Peirce's law: can any qq prove it? The graph measures success rate on eleven theorems.

Three lessons from the figure extend to real systems. First, with enough budget even a random policy eventually finds short proofs, because the verifier prunes invalid steps; policy quality is measured by compute saved. Second, most calls from a mediocre policy go to tactics that cannot even apply, exactly what happens when language models invent lemma names. Third and most important, Peirce’s law is proved by no qq or budget. The policy can be arbitrarily biased; a correct verifier finds only what is true.

From GPT-f to DeepSeek-Prover-V2

GPT-f (Polu and Sutskever, 2020) was the first transformer-based system of this kind. It generated Metamath tactics with a language model trained on the library and combined them with best-first search guided by accumulated log probability, as in the figure. Some proofs it found were shorter than existing ones and entered the main Metamath library.

LeanDojo (Yang et al., 2023) opened the problem: an environment for programmatic Lean interaction, a mathlib-derived dataset, and a prover, ReProver, that retrieves relevant library lemmas before proposing a tactic. Retrieval addresses the crosses in the figure: with hundreds of thousands of lemmas, knowing what exists and its name is the bottleneck. The dataset includes a split where every evaluation proof uses a lemma absent from all training proofs, measuring generalization rather than memory.

AlphaProof (Hubert et al., 2025) applies AlphaZero with Lean as environment. A fine-tuned Gemini translates natural-language statements into Lean to create a large formal problem set, and AlphaProof learns by reinforcement to prove or refute them: each kernel-accepted proof becomes a new training example. At the 2024 International Mathematical Olympiad, AlphaProof solved three of six problems (two algebra, one number theory) and AlphaGeometry 2 solved one geometry problem, scoring 28 of 42 points at the high end of the silver-medal range (DeepMind, 2024). Two qualifications matter: statements were translated into Lean by hand, and some problems took up to three days of compute versus two four-and-a-half-hour sessions for contestants, with reinforcement learning during the test on variants of each problem.

DeepSeek-Prover-V2 (Ren et al., 2025) generates complete proofs rather than tactics and tackles hard problems by decomposing them into subgoals: a general model writes a Lean proof sketch with intermediate lemmas (have with proofs pending), a smaller model proves each lemma separately, and solved proofs combined with their motivating informal reasoning provide initial training before verifier-reward reinforcement. It reports 88.9% proofs found on miniF2F’s test split and 49 of 658 PutnamBench problems, using thousands of samples per problem. The low fraction of university-level Putnam problems solved while miniF2F nears its ceiling says much about which problems are already solved and which are not.

Comparison with AlphaZero

AlphaZero (games)LLM prover
board positionproof state (open goals)
legal movetactic accepted by assistant
game rules, which nobody learnsassistant kernel, which nobody should learn
policy network π(a∣s)\pi(a \given s)language model proposing tactics
value network v(s)v(s)estimate of proof proximity (or whether the goal is provable)
MCTS with simulationsbest-first search or MCTS with verifier calls
victoryclosed proof accepted by kernel
self-playattempt to prove or refute new statements and learn from found proofs

The analogy has a limit. In chess the rules guarantee a legal move is a move; in mathematics the kernel guarantees a correct proof of the formal statement. Nobody guarantees the formal statement is the intended problem. The AlphaZero algorithm and its use in discovering proofs (learned search for discovery) are studied in the reinforcement-learning module, and verifier reward in verifiable rewards.

A toy prover

The laboratory reproduces the architecture minimally. Its tactic language has two parts: the figure’s propositional tactics (intro, constructor, left, right, exact, apply, cases) and rewrites for equalities between expressions with ++ and ⋅\cdot, with seven lemmas (commutativity, associativity, distributivity, identities) applicable anywhere. ejecutar is the verifier: it returns new goals or None. Search receives a function puntuar(estado) estimating how much remains; a real system uses the model in this role.

[ ]A toy prover: tactics and verifierBrowser
import heapq

def tacticas_prop(goal):
    """Tácticas sintácticamente posibles sobre un objetivo proposicional (válidas o no)."""
    _, hyps, T = goal
    yield ('intro',)
    yield ('constructor',)
    yield ('left',)
    yield ('right',)
    for i in range(len(hyps)):
        yield ('exact', i)
        yield ('apply', i)
        yield ('cases', i)

def ejecutar_prop(goal, tac):
    """Verificador de las tácticas proposicionales: nuevos objetivos, o None si no se puede aplicar."""
    _, hyps, T = goal
    mk = lambda hs, t: ('prop', tuple(sorted(set(hs), key=repr)), t)
    op = T[0] if isinstance(T, tuple) else None
    if tac[0] == 'intro':
        return [mk(hyps + (T[1],), T[2])] if op == '->' else None
    if tac[0] == 'constructor':
        return [mk(hyps, T[1]), mk(hyps, T[2])] if op == '*' else None
    if tac[0] in ('left', 'right'):
        return [mk(hyps, T[1] if tac[0] == 'left' else T[2])] if op == '+' else None
    h = hyps[tac[1]]
    resto = hyps[:tac[1]] + hyps[tac[1] + 1:]
    if tac[0] == 'exact':
        return [] if h == T else None
    if tac[0] == 'apply':                     # h : S1 → ... → Sn → T deja los objetivos S1, ..., Sn
        args = []
        while h != T:
            if not (isinstance(h, tuple) and h[0] == '->'):
                return None
            args.append(h[1])
            h = h[2]
        return [mk(hyps, a) for a in args]
    if tac[0] == 'cases':
        if h == 'bot':
            return []
        if isinstance(h, tuple) and h[0] == '*':
            return [mk(resto + (h[1], h[2]), T)]
        if isinstance(h, tuple) and h[0] == '+':
            return [mk(resto + (h[1],), T), mk(resto + (h[2],), T)]
    return None

# Reescritura: (nombre, patrón, resultado); las variables de patrón empiezan por '?'
REGLAS = [
    ('add_comm', ('+', '?x', '?y'), ('+', '?y', '?x')),
    ('add_assoc', ('+', ('+', '?x', '?y'), '?z'), ('+', '?x', ('+', '?y', '?z'))),
    ('add_assoc←', ('+', '?x', ('+', '?y', '?z')), ('+', ('+', '?x', '?y'), '?z')),
    ('mul_comm', ('*', '?x', '?y'), ('*', '?y', '?x')),
    ('mul_add', ('*', '?x', ('+', '?y', '?z')), ('+', ('*', '?x', '?y'), ('*', '?x', '?z'))),
    ('add_zero', ('+', '?x', '0'), '?x'),
    ('mul_one', ('*', '?x', '1'), '?x'),
]

def encaja(pat, t, s):
    if isinstance(pat, str) and pat.startswith('?'):
        if pat in s:
            return s if s[pat] == t else None
        return {**s, pat: t}
    if isinstance(pat, str) or isinstance(t, str):
        return s if pat == t else None
    if pat[0] != t[0]:
        return None
    s = encaja(pat[1], t[1], s)
    return None if s is None else encaja(pat[2], t[2], s)

def instanciar(pat, s):
    return s.get(pat, pat) if isinstance(pat, str) else (pat[0], instanciar(pat[1], s), instanciar(pat[2], s))

def posiciones(t, camino=()):
    yield camino
    if isinstance(t, tuple):
        yield from posiciones(t[1], camino + (1,))
        yield from posiciones(t[2], camino + (2,))

def en(t, camino):
    for i in camino:
        t = t[i]
    return t

def reemplazar(t, camino, nuevo):
    if not camino:
        return nuevo
    i = camino[0]
    return t[:i] + (reemplazar(t[i], camino[1:], nuevo),) + t[i + 1:]

def tacticas_eq(goal):
    yield ('rfl',)
    for lado in (1, 2):
        for camino in posiciones(goal[lado]):
            for r in range(len(REGLAS)):
                yield ('rw', r, lado, camino)

def ejecutar_eq(goal, tac):
    if tac[0] == 'rfl':
        return [] if goal[1] == goal[2] else None
    _, r, lado, camino = tac
    _, pat, res = REGLAS[r]
    s = encaja(pat, en(goal[lado], camino), {})
    if s is None:
        return None
    nuevo = list(goal)
    nuevo[lado] = reemplazar(goal[lado], camino, instanciar(res, s))
    return [tuple(nuevo)]

def tacticas(estado):
    return tacticas_prop(estado[0]) if estado[0][0] == 'prop' else tacticas_eq(estado[0])

def ejecutar(estado, tac):
    g, resto = estado[0], estado[1:]
    nuevos = ejecutar_prop(g, tac) if g[0] == 'prop' else ejecutar_eq(g, tac)
    return None if nuevos is None else tuple(nuevos) + resto

def buscar(objetivo, puntuar, presupuesto):
    """Primero el mejor con coste = profundidad + puntuar(estado). Cada táctica probada es una llamada
    al verificador. Devuelve (demostrado, llamadas, guion)."""
    inicio = (objetivo,)
    orden = itertools.count()
    frontera = [(puntuar(inicio), next(orden), 0, inicio, [])]
    vistos, llamadas = {inicio}, 0
    while frontera:
        _, _, prof, estado, guion = heapq.heappop(frontera)
        for tac in tacticas(estado):
            if llamadas == presupuesto:
                return False, llamadas, None
            llamadas += 1
            nuevo = ejecutar(estado, tac)
            if nuevo is None or nuevo in vistos:
                continue
            if not nuevo:
                return True, llamadas, guion + [tac]
            vistos.add(nuevo)
            heapq.heappush(frontera, (prof + 1 + puntuar(nuevo), next(orden), prof + 1, nuevo, guion + [tac]))
    return False, llamadas, None

ok, n, guion = buscar(('prop', (), arr(arr(A, B), arr(neg(B), neg(A)))), lambda e: 0, 500)
print(f"contrarrecíproco por búsqueda en anchura: {ok}, {n} llamadas, guion {guion}")

Now the experiment: fourteen theorems, seven propositional and seven equational, with two strategies. Breadth-first search uses puntuar = 0; guided search uses a handwritten heuristic measuring what remains (the size of propositional goals not already among assumptions, and positions where two equality sides differ).

[ ]How much does a good heuristic help?Browser
def tam_tipo(t):
    return 1 if isinstance(t, str) else 1 + tam_tipo(t[1]) + tam_tipo(t[2])

def preorden(t):
    return [t] if isinstance(t, str) else [t[0]] + preorden(t[1]) + preorden(t[2])

def heuristica(estado):
    """Puntuación a mano de cuánto falta. En un sistema real, este es el papel del modelo."""
    h = 0
    for g in estado:
        if g[0] == 'prop':
            h += 0 if g[2] in g[1] else tam_tipo(g[2])
        else:
            a, b = preorden(g[1]), preorden(g[2])
            h += sum(x != y for x, y in zip(a, b)) + abs(len(a) - len(b))
    return 2 * h

uniforme = lambda estado: 0

P = lambda T: ('prop', (), T)
E = lambda l, r: ('eq', l, r)
su = lambda x, y: ('+', x, y)
mu = lambda x, y: ('*', x, y)
bateria = {
    "composición": P(arr(arr(A, B), arr(arr(B, C), arr(A, C)))),
    "∧ conmutativa": P(arr(('*', A, B), ('*', B, A))),
    "∨ conmutativa": P(arr(('+', A, B), ('+', B, A))),
    "contrarrecíproco": P(arr(arr(A, B), arr(neg(B), neg(A)))),
    "¬¬ tercero excluido": P(neg(neg(lem))),
    "De Morgan": P(arr(neg(('+', A, B)), ('*', neg(A), neg(B)))),
    "distributiva": P(arr(('+', A, ('*', B, C)), ('*', ('+', A, B), ('+', A, C)))),
    "a + b = b + a": E(su('a', 'b'), su('b', 'a')),
    "(a + b) + c = a + (b + c)": E(su(su('a', 'b'), 'c'), su('a', su('b', 'c'))),
    "a + (b + c) = c + (b + a)": E(su('a', su('b', 'c')), su('c', su('b', 'a'))),
    "a·(b + c) = a·c + a·b": E(mu('a', su('b', 'c')), su(mu('a', 'c'), mu('a', 'b'))),
    "(a + 0)·1 = a": E(mu(su('a', '0'), '1'), 'a'),
    "(a + b)·c = c·b + c·a": E(mu(su('a', 'b'), 'c'), su(mu('c', 'b'), mu('c', 'a'))),
    "a + b + c + d = d + c + b + a": E(su(su(su('a', 'b'), 'c'), 'd'), su(su(su('d', 'c'), 'b'), 'a')),
}

presupuestos = [50, 200, 1000, 5000, 20000]
resultados = {}
for nombre, g in bateria.items():
    for etiqueta, f in [("anchura", uniforme), ("heurística", heuristica)]:
        ok, llamadas, _ = buscar(g, f, max(presupuestos))
        resultados[nombre, etiqueta] = llamadas if ok else None

print(f"{'llamadas hasta la prueba':32s} {'anchura':>9s} {'heurística':>11s}")
for nombre in bateria:
    fila = [resultados[nombre, e] for e in ("anchura", "heurística")]
    print(f"{nombre:32s} " + " ".join(f"{(str(x) if x else 'fallo'):>10s}" for x in fila))
print(f"\nTasa de éxito por presupuesto ({len(bateria)} teoremas):")
for b in presupuestos:
    tasas = [sum(1 for n in bateria if resultados[n, e] is not None and resultados[n, e] <= b) for e in ("anchura", "heurística")]
    print(f"  {b:6d} llamadas: anchura {tasas[0]:2d}/{len(bateria)}   heurística {tasas[1]:2d}/{len(bateria)}")

ok, n, guion = buscar(bateria["a + (b + c) = c + (b + a)"], heuristica, 5000)
print("\nGuion para a + (b + c) = c + (b + a):")
for tac in guion:
    lado = 'izquierdo' if len(tac) > 2 and tac[2] == 1 else 'derecho'
    print("  ", "rfl" if tac[0] == 'rfl' else f"rw {REGLAS[tac[1]][0]} en el lado {lado}, posición {tac[3]}")

For propositional theorems the heuristic changes little (at best halves calls for distributivity): search spaces are small and breadth-first already traverses them in tens or hundreds of calls. For equational theorems, where each state allows dozens of rewrites, the difference reaches nearly an order of magnitude: a+(b+c)=c+(b+a)a + (b + c) = c + (b + a) needs 2202 calls unguided and 285 guided, and reversal of four summands exhausts 20000 breadth-first calls while guided search solves it in 6931. With 200 calls, guidance raises the count from 8 to 10 of 14 theorems. This is the design role a language model replaces: tacticas (propose promising actions rather than enumerate all) and puntuar (estimate state value). What it never replaces is ejecutar. An absurd heuristic makes search slow; if ejecutar accepted a rewrite that did not match, the system would “prove” falsehoods and no amount of compute would detect it.

Autoformalization and benchmarks

The bottleneck is that mathematics is written in natural language while assistants require formal statements.

Wu et al. (2022) showed a large language model perfectly translated 25.3% of a competition-problem sample into Isabelle/HOL, and that training a prover on resulting statements raised its miniF2F rate from 29.6% to 35.2%: imperfect autoformalization already helps produce training data. miniF2F (Zheng et al., 2021) has 488 statements from AIME, AMC, and the International Olympiad plus high-school and early undergraduate problems, formalized in several systems and split into validation and test. PutnamBench (Tsoukalas et al., 2024) manually formalizes Putnam competition problems in Lean 4, Isabelle, and Rocq, at a clearly higher level.

Three risks can make a high score meaningless:

  • Incorrectly formalized statements. In Lean, natural-number subtraction truncates at zero and division by zero equals zero, so ∀ n : ℕ, n - 1 + 1 = n is false (at n=0n = 0 it gives 11) and ∀ x : ℝ, x / x = 1 is too (at x=0x = 0 it gives 00). Contradictory assumptions are more treacherous: if a formalization requires both x>0x > 0 and x<0x < 0, any conclusion is provable and the system scores a success without doing the intended work. Successive miniF2F versions have corrected such statements.
  • Contamination. Benchmarks are public and their statements, sometimes proofs, enter model training data. A high score on a benchmark published before the data cutoff partly measures memory.
  • Holes and axioms. A proof that compiles may use sorry, an added axiom, or native_decide. Serious evaluation checks each proof’s axioms, not merely whether the file compiles.

Mitigations are known, though not automatic: human review of statements (or at least a sample), back-translation into natural language for comparison with the original, attempting to prove the negation and checking assumptions satisfiable (a concrete counterexample exposes a false statement, and a model rules out contradictory assumptions), evaluation on problems after the model’s cutoff, and an axiom allowlist. There is no verifier for “this formal statement says what the informal one says”: this link in the chain remains human. The role of counterexample search in statement validation returns in the methodology module.

Learning-guided solvers

The same division appears in classical automated reasoning. Modern SAT solvers use DPLL with clause learning and many heuristics: which variable to decide, which learned clauses to forget, when to restart. These are natural candidates for learning.

NeuroSAT (Selsam et al., 2018) is a message-passing network over the bipartite literal–clause graph trained only to predict one bit: whether the formula is satisfiable. Yet for many satisfiable instances a satisfying assignment can be read from internal states, and more iterations solve problems larger than training examples; the authors say it does not compete with real solvers. Selsam and Bjørner’s later NeuroCore (2019) changed goals: rather than solve, predict variables appearing in an unsatisfiable core and periodically adjust MiniSat, Glucose, and Z3 decision heuristics. With this change MiniSat solved 10% more 2018 SAT competition problems under the same time limit.

The lesson’s moral is consistent. The network never decides the answer: a proposed assignment is evaluated in linear time; if the solver says “unsatisfiable,” it can emit a resolution proof in DRAT format, verified independently. SAT competitions require these certificates, and formally verified DRAT checkers exist. Learning enters heuristics, where an error costs time, never verification, where an error costs correctness.

Open questions

  • Generated and verified code. If a model writes a program, it can also write its specification and correctness proof (in Lean, Dafny, or Verus), checked by a verifier. Lesson 9’s verification conditions discharge automatically; the hard part is inventing loop invariants. Proposing invariants suits models because an incorrect proposal is detected.
  • Who verifies the specification? This shifts trust from proof to statement. A model writing code, specification, and proof can write a trivial specification. This is formal reward hacking: optimizing against a perfect verifier of a badly written goal.
  • Beyond competitions. miniF2F is nearly saturated; research problems require definitions and theory absent from any library. Formalizing the right definition, rather than merely proving a given statement, is much harder to evaluate.
  • Imperfect verifiers. Outside formal mathematics, verifiers are learned models or incomplete tests, weakening the generation–verification asymmetry. This and the general generation–verification gap are covered in the reasoning module.

Common mistakes

Exercises

ProofThe S combinator as term and derivation
Prove: Construct a closed term of type (A→B→C)→(A→B)→A→C(A \to B \to C) \to (A \to B) \to A \to C and its corresponding natural-deduction derivation.
0
The type is an implication with three antecedents, A→B→CA \to B \to C, A→BA \to B and AA, and consequent CC.

Step 1 of 4. Where do you start?

QuizWhy trust a generated proof?
A language model generates Lean proofs and gets most attempts wrong. Yet a proof accepted by Lean's kernel is considered reliable. What is the correct explanation and its limits?
CodeThe complete type checker
Implement typecheck(term, ctx) for simply typed λ-calculus with products and sums, using the laboratory representation. Types: strings (atoms, and 'bot' for ⊥) or tuples ('->', S, T), ('*', S, T) and ('+', S, T). Terms: ('var', x), ('lam', x, T, cuerpo), ('app', t, u), ('pair', t, u), ('fst', t), ('snd', t), ('inl', t, B) (of type ('+', tipo de t, B)), ('inr', A, t), ('case', t, x, u, y, v) and ('abort', t, T). ctx is a dictionary from names to types. Return the type or raise TypeError for an ill-typed term or unbound variable. An inner binding shadows an outer binding of the same name.
def typecheck(term, ctx):
  """Devuelve el tipo de term en el contexto ctx, o lanza TypeError."""
  tag = term[0]
  # tu código: un caso por construcción
  raise NotImplementedError(tag)
Shift+Enter to run
QuizWhat is provable without classical logic?
Which formulas are provable in intuitionistic propositional logic (with AA and BB distinct atoms)?

More than one answer may be correct.

NumericHow many distinct proofs?
How many closed normal-form terms (identifying those differing only in bound-variable names) inhabit type A→A→AA \to A \to A?
Proofrev (rev l) = l by structural induction
Prove: With rev [] = [] and rev (a :: as) = rev as ++ [a], prove rev (rev l) = l for every list l as a sequence of tactics.
0
Lists are the inductive type with constructors [] and ::, and ++ is defined recursively on its first argument.

Step 1 of 5. Which principle directly matches the definition of rev, which recurses on the tail?

Quiz90% on a formal benchmark
A system reports proving 90% of problems in a formal benchmark published before its training. What should be checked before believing this measures proving ability?

More than one answer may be correct.

NumericSampling many times
A model generates complete proofs of a problem requiring 8 tactics; suppose it gets each tactic right independently with probability 0.6 and only a sequence of 8 correct tactics is a proof. With 32 independent samples, each checked by the verifier, what is the probability of finding at least one proof (pass@32)?

Summary

Key idea
A proof is a program and checking it is type checking: a small kernel can certify proofs from any source, so AI provers can use an unreliable generator provided the verifier is exact and the statement expresses the intended claim.
  • Simply typed λ-calculus has unique decidable typing, type preservation, and strong normalization; every well-typed program terminates, so the language is not Turing complete.
  • Curry–Howard: propositions are types, proofs terms, →I{\to}\mathrm{I} is λ\lambda, →E{\to}\mathrm{E} is application, ∧\land is product, ∨\lor is sum, ⊥\bot is the empty type, and eliminating a detour is a β-reduction step.
  • Normalization yields consistency (no closed terms of type ⊥\bot) and shows excluded middle and Peirce’s law are not intuitionistic; classical logic is added as a computationally empty axiom or a control operator.
  • A proof assistant separates a small kernel (de Bruijn criterion) from tactics and automation building terms; the trusted base is kernel, axioms, and statement. Structural induction applies a recursor, and function termination is logical consistency.
  • Language-model provers combine a tactic-proposing policy, search (best-first, MCTS, massive sampling), and the assistant as verifier and reward: GPT-f, LeanDojo, AlphaProof, and DeepSeek-Prover-V2 vary this scheme.
  • Autoformalization and benchmarks shift trust to the statement: check formalization, contamination, axioms, and budget. Learning-guided solvers follow the same rule: learning for heuristics, verification through certificates.