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 : 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 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:
- A minimal programming language, simply typed λ-calculus, with its type checker.
- The Curry–Howard correspondence: that type checker is a proof checker for intuitionistic natural deduction, and executing a program simplifies a proof.
- How this scales to a real proof assistant (Lean 4), with its trusted kernel and tactics, and how it performs structural induction.
- 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 . Types are generated by the grammar
and terms, with variables , by
Both are inductive definitions, so everything that follows is proved by structural induction. is the function mapping to (in Python, lambda x: t with a type annotation), applies to , is a pair and its projections; and tag a value as left or right in a disjoint union and examines it; is the empty type and says that, given a value of empty type, you could make anything. We abbreviate as . Application associates left () and the arrow right (), so a two-argument function returns a function.
A context assigns types to variables. The judgment (“in context , has type ”) has one rule per construction:
with symmetric to . The rule names are no accident, as you will see. To determine the type of and , the implementation annotates the other side of the sum and the target type; the text omits them.
Two examples: has type : it receives an , then an , and returns the . has type : it swaps a pair. By contrast has no type for any : to apply to anything, would have to be a function , and for the argument to fit, , 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 .
β-reduction
Executing a program simplifies its redexes: a constructor immediately followed by its destructor.
and the symmetric rule for . Reduction applies in any subterm. Substitution replaces free occurrences of with and renames binders in that would capture free variables of : 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 . The rules are syntax-directed: each form of matches exactly one rule’s conclusion, whose premises concern immediate subterms. For a variable, the type is assigned by (if absent, there is no type). For , the induction hypothesis gives at most one with , and the type is . For , compute the types of and (unique by hypothesis); a type exists exactly when that of has form with equal to that of , and then it is . The remaining cases are similar; in both branches must have the same type. The recursion is structural, so it terminates.
∎Proof
The key case is the root redex . By the rules, and . The substitution lemma says that then , proved by induction on the derivation of : replace each leaf of that derivation using assumption by the entire derivation of ; 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 fragment. First, why the naive idea fails: counting redexes or measuring size is insufficient, because contracting duplicates 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 fragment, Turing–Prawitz argument.) Call the degree of a redex the size of the function type . Contraction can create new redexes in only three ways: (i) if contains and is a λ, appears, of degree ; (ii) if is a λ and the whole redex was applied, has degree ; (iii) if and is a λ later applied, likewise with degree . Other redexes of were already in or are copies of those in . Let be the maximum degree of redexes of and the count of degree . Choose one of degree containing no other of degree in its argument (one exists: among degree redexes, take the one starting rightmost in the term). On contraction it disappears, new ones have degree below , and copies of contain none of degree . The pair 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: remains, and each rule is exactly a natural-deduction rule from lesson 4. introduces implication (assume , derive , discharge), is modus ponens, and concern conjunction, is reasoning by cases, and is ex falso. Terms are a linear notation for derivation trees.
| Logic (natural deduction) | Programming (typed λ-calculus) |
|---|---|
| proposition | type |
| proof of | term (program) of type |
| open assumption | free variable |
| discharge assumption () | bind with |
| modus ponens () | function application |
| pair: product type | |
| , proof by cases | disjoint union, |
| , ex falso | empty type, |
| function | |
| eliminate a detour | one β-reduction step |
| normal proof | program in normal form |
| check a proof | check the type |
Proof
Erasing terms from a derivation of gives a logical derivation: each typing rule becomes the logical rule of the same name, and a variable bound by marks an assumption discharged with label . Conversely, given a logical derivation with labeled assumptions, construct the term by induction on the derivation: an assumption labeled is variable , an is 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.
Build composition in the figure: with assumptions , and already introduced, the hole asks for . The only rule concluding applies , leaving a hole of type ; the only one concluding applies , leaving one of type , and closes it. The resulting term 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 by assuming and immediately use it with modus ponens, or prove only to retain . Dag Prawitz proved in 1965 that every detour can be eliminated, and his procedure is β-reduction rule by rule:
On the left, instead of assuming and discharging it, paste the proof of at every leaf; on the right, substitute by . For conjunction, discards the unused half’s proof; for disjunction, 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 (, , , ) whose principal argument is neutral. By structural induction every typed normal term is either an introduction (, pair, , ) 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 , normalization and preservation give a normal, closed with . Being closed it is not neutral, so is an introduction. But no introduction has type : has no introduction rule.
∎The same argument gives finer negative results without semantics:
Proof
Excluded middle. A closed normal term of type is an introduction: with closed and normal, impossible because would be an introduction and atoms have none; or with . Then with normal. is not an introduction (there are none for ), so is neutral with head . But no elimination applies to (it is not a function, pair, sum, or ), so , of type . Contradiction.
Peirce. A closed normal term is with . is neutral with head (the only variable), and the only elimination possible on is application: , already of type and allowing no more eliminations. Then is normal. If were neutral, its head would be and its type , not ; so with . is neutral, with head (type , allowing no elimination) or (type after application). Neither gives .
∎Both formulas are classical tautologies: what fails is that an intuitionistic proof of must decide which side holds, and without knowing anything about there is no way. By contrast there is a term for :
Read it as a program with a clever strategy: promises to refute any proof of . The term first supplies “,” as a function that, if it ever receives an , goes back and gives the proof . Glivenko proved in 1929 that this is general in propositional logic: is a classical tautology if and only if 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: in the context. With it, Peirce has an inhabitant:
An axiom has no computational content: a term using it gets stuck at , because is neither nor . 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 , and .
# 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, , cites a nonexistent assumption, and the third, , is the self-application forbidden by the type system. Disjunction remains (, , ). 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.
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. is identity: in logic, a derivation of 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 holds in if in every world after where holds, holds too. Intuitionistic logic is sound and complete for these models, as classical logic is for valuations.
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 , is not yet true, but neither is , because in the next world will be true. This is Kripke’s reading of “we do not know yet.” In the same world , by contrast, 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 is a function that for each returns a proof of : its type is a function type whose result type depends on the argument. A proof of is a pair: a witness and a proof of , of type . 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 goal”) into another while leaving a piece of term. intro is , apply h is read backward (to prove with , suffice to prove ), exact closes with a term, cases is . 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:
- The kernel, and the hardware and compiler running it. It is small, carefully reviewed, and checkable with independent implementations.
- Axioms. Lean has three: propositional extensionality (
propext), quotient (Quot.sound), and choice (Classical.choice). Command#print axioms tlists those used by the proof oft. Any other is a warning:sorryAxmeans ansorry(a manually filled hole) somewhere in the lemma chain, andLean.ofReduceBoolmeansnative_decidewas used, trusting the compiler as well as the kernel. - 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):
If takes values in Prop, it is the induction principle: from a proof of and a function turning proofs of into proofs of comes a proof of for every . If 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 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.
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
The problem as search
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 : 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.
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 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 position | proof state (open goals) |
| legal move | tactic accepted by assistant |
| game rules, which nobody learns | assistant kernel, which nobody should learn |
| policy network | language model proposing tactics |
| value network | estimate of proof proximity (or whether the goal is provable) |
| MCTS with simulations | best-first search or MCTS with verifier calls |
| victory | closed proof accepted by kernel |
| self-play | attempt 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 , 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.
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).
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: 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 = nis false (at it gives ) and∀ x : ℝ, x / x = 1is too (at it gives ). Contradictory assumptions are more treacherous: if a formalization requires both and , 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, ornative_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
Step 1 of 4. Where do you start?
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)More than one answer may be correct.
Step 1 of 5. Which principle directly matches the definition of rev, which recurses on the tail?
More than one answer may be correct.
Summary
- 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, is , is application, is product, is sum, is the empty type, and eliminating a detour is a β-reduction step.
- Normalization yields consistency (no closed terms of type ) 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.