Proof techniques and natural deduction
Review proof techniques—direct proof, contraposition, contradiction, cases, existence, and counterexample—as goal-oriented strategies. Formalize them as natural deduction rules and state propositional soundness and completeness, bridging proof and truth.
After this lesson you can
- Choose and apply the right technique for a statement's logical form.
- Write readable proofs with explicit hypotheses and goals.
- Construct natural-deduction derivations while managing open and discharged assumptions.
- Explain propositional soundness and completeness (⊢ versus ⊨).
- Distinguish constructive and nonconstructive proofs and implications for algorithms.
- Refute conjectures with minimal counterexamples.
Before you start
Motivation: a proof is an object someone checks
In the first lesson you decided whether by examining all valuations: a truth table with rows. In the second, quantifiers over infinite domains remove that option: “for every integer ” cannot be checked case by case. Mathematics replaces exhaustive checking with a finite proof anyone can review step by step without rediscovering it.
The idea of a proof as an object checked by a verifier is more than a formality:
- Algorithm correctness is proven with loop invariants and variant functions, as in the invariants lesson. A gap can hide exactly the case in which the program fails.
- Generalization bounds in learning theory, such as the test-set bound, are inequality chains whose steps use techniques from this lesson. Reading a theory paper requires recognizing each step’s strategy and spotting when a step does not follow, practiced in research as gap detection.
- Proof assistants (Lean, Coq, Isabelle) and systems that search for proofs using neural networks use a small kernel accepting or rejecting each step. To a machine a poorly structured proof is not “almost correct”: it does not compile.
A proof-assistant interface captures the craft. At each point you have hypotheses (what may be used) and a goal (what remains to prove), and each step transforms the pair:
The lesson has two halves. First review standard proof techniques (direct, contraposition, contradiction, cases, existence, counterexample) as goal strategies selected by logical form. Then convert them into rules of a formal system, natural deduction, write a checker, and prove the theorem uniting the halves: what can be proven is exactly what is true, and coincide.
Logical form dictates strategy
The most useful advice for starting a proof is syntactic rather than mathematical: look at the goal’s main connective. Every connective has a natural proof form saying what can be assumed and what remains. Every connective in a hypothesis also has a natural use. The tables summarize both sides; most mathematics-course proofs combine these rows.
| If the goal is | Strategy | Hypothesis gained | Remaining goal |
|---|---|---|---|
| direct | |||
| contrapositive | |||
| assume the assertion | |||
| (any) | contradiction | ||
| fix arbitrary | , nothing more | ||
| give witness | |||
| two goals | , then | ||
| choose a side, or assume | nothing, or | chosen side, or | |
| two conditionals | and |
| If a hypothesis is | Use it as follows |
|---|---|
| separate into and | |
| cases: prove the goal assuming , then assuming | |
| with (or a proof of it), obtain | |
| instantiate at any concrete object: | |
| introduce a fresh name with property | |
| deriving gives contradiction; or rewrite using negation laws |
The and rows are asymmetric. To prove fix an about which nothing but its type is known: proving without using anything particular about that makes the argument universal. To use hypothesis name an existing object, but you cannot choose it: the name must be fresh, distinct from everything already present.
Real proofs are not linear: sometimes a strategy stalls and you backtrack. The first interactive is a small proof assistant with five statements. Some paths close every goal; others stall, and the panel explains why.
What you should see:
- The right strategy depends on information flow. With odd , and can be calculated; with even there is no algebraic route to . Contraposition reverses calculation direction and makes it easy.
- Contraposition does not always help. For divisibility transitivity it changes strong hypotheses (, which give witnesses for calculation) into weak ones (, which do not). Hypothesis form matters as much as goal form.
- Several strategies may close the same goal at different quality. Contradiction for “even implies even ” works but disguises contraposition; cases work, but one is trivial and the other contraposition under another name.
Contraposition and contradiction
Contrapositive is not the converse. The converse of is , not equivalent: with false and true , holds and does not. Proving the converse instead is a common mistake; the natural-deduction builder shows no sound rule system permits the conversion.
Informal language mixes two patterns under this name; distinguish them because they become separate rules later:
- Negation introduction. To prove , assume and reach . No double negation: this defines what refuting means.
- Contradiction proper. To prove , assume , reach , and conclude ; the last step from to is a classical principle intuitionistic logic rejects.
Irrationality of is the first type: the claim is a negation, . It needs a lemma proven in the interactive: if is even, so is . Build the proof step by step.
Step 1 of 4. How do you begin?
The classic proof by contradiction is older still and hides a surprise.
Proof
Let . Since , it has a prime divisor (its least divisor greater than is prime). If were one of , it would divide and , hence their difference : impossible. Thus is not on the list. If primes were finite, listing all would yield contradiction.
∎Surprisingly, read correctly Euclid’s argument is direct and constructive: given any list it builds a new prime (factor and take a factor). Contradiction appears only in the last sentence and is dispensable. Two cautions. First, need not be prime: . Second, presenting a direct argument as contradiction is not logically wrong, but hides algorithmic content.
Cases, existence, and knowing that versus knowing which
The most useful cases come from a known disjunction about the problem. For “” use division remainders , , or ; each calculation closes:
Odd/even cases would not help: cases must address the divisor. With finitely many but many cases, this becomes proof by exhaustion only a computer can traverse. The four-color theorem (Appel and Haken, 1976) was the first famous example; Kepler’s sphere-packing conjecture was settled with a formal proof checked by proof assistants (Hales et al., 2015). Case exhaustiveness is part of the proof and must be justified like any step.
The canonical nonconstructive proof fits in three lines. Build it:
Step 1 of 4. What strategy do you use?
The difference has practical consequences. A constructive existence proof is an algorithm: Euclid computes a new prime, divisibility transitivity computes quotient . A nonconstructive proof may give none. An extreme example is if Goldbach’s conjecture is true and otherwise: it is computable because it is one of two constant functions, yet nobody knows how to write its program. The idea that constructively proving means writing a program returning is central to the Curry–Howard correspondence; proof assistants use it to extract programs from proofs.
Counterexamples: why a thousand cases are not proof
By quantifier laws, : one case refutes a universal claim. The asymmetry is total. One failure refutes forever; a million successful cases prove nothing about the infinitely many remaining.
Mathematical history is full of conjectures surviving many cases. The second interactive lets you bet against four.
The four conjectures teach different lessons:
- gives primes for (Euler, 1772), failing at with . This is not accidental: if an integer-coefficient polynomial equals prime at some , then for every , because ; a nonconstant polynomial takes values only finitely often, so some is composite. No nonconstant integer-coefficient polynomial gives only primes.
- Fermat numbers are prime for , and Fermat conjectured all were. Euler found factor of in 1732. Five supporting cases were more wish than evidence.
- Circle regions follow then . The correct formula matches while : initial sequence terms do not determine it.
- for prime fails at . The converse is true: if is prime, is prime. Confusing a conditional and converse becomes a conjecture.
Some counterexamples are much more elusive. Pólya’s conjecture about sign of Liouville-function sum first fails at . Mertens’s conjecture was refuted in 1985 (Odlyzko and te Riele) without exhibiting a counterexample: one was proven to exist nonconstructively, and none has been calculated. No amount of computer checking would convert those conjectures into theorems.
Natural deduction: strategies as rules
So far techniques were informal: Spanish sentences accepted by a human reader. For a machine to check a proof, or to prove things about proofs, a formal system is needed. Gerhard Gentzen and Stanisław Jaśkowski independently proposed one in 1934 that imitates mathematical reasoning rather than reducing it to few axioms: natural deduction.
Rules are precisely the strategy-table rows. Box rules (→I and ¬I) open and discharge assumptions; in Fitch style an assumption heads a box and its discharging rule follows the box’s last line.
| Connective | Introduction (how to prove) | Elimination (how to use) | Informal technique |
|---|---|---|---|
| two goals; separate | |||
| choose a side; cases | |||
| direct; modus ponens | |||
| assume and refute | |||
| anything from contradiction | |||
| classical | contradiction |
Three comments. First, our E cites two conditionals instead of two boxes; it is equivalent to textbooks’ two-box version because each box is precisely a →I subproof, and lets only →I and ¬I close boxes, simplifying the checker. Second, contraposition needs no separate rule because it is a derivable theorem. Third, classical E is the only rule not read as “one connective, one strategy.” Without it there is intuitionistic logic, where neither nor is provable; with it, classical truth-table logic.
Here is a Fitch-style derivation of contraposition, :
And as a tree, with assumptions as leaves: each leaf is discharged by the rule marked .
Both notations describe the same object. Fitch is more compact (a multiply cited line is written once) and used by checkers; trees show dependencies because leaves are assumptions. Build them yourself.
What you should see:
- Every box is a scope. While an assumption is open, everything derived depends on it; after →I or ¬I discharges it, box lines become unavailable. Programmers recognize local-variable scope: a parameter exists only inside its function, and →I is literally the abstraction creating that function. See Curry–Howard.
- Read strategy bottom up. To prove a conditional assume its antecedent and close with →I; for negation assume the assertion and seek . Introduction rules build the goal, elimination rules consume hypotheses, and a good proof meets in the middle.
- Each line follows from its open assumptions. Tap any line: the truth table always confirms . This observation as a theorem is system soundness.
- Excluded middle needs the classical rule. The solution for uses E; the others do not. De Morgan one way, , and the other, , are intuitionistically valid.
Soundness and completeness: the bridge between ⊢ and ⊨
There are two notions of “follows.” One is semantic: , logical consequence, defined using valuations and silent about reasoning. The other is syntactic: , a derivation exists, a finite object checked without considering truth values. Their coincidence is not obvious and gives meaning to everything above.
Proof
Take a Fitch derivation with lines , premises in , and no box open at the end. For each line , let be assumptions of boxes containing it (open at that point). By strong induction on prove invariant
Two facts apply throughout. Monotonicity: if and , then . Accessibility: a line citable at line is in no closed box, so all its boxes remain open at : , and induction plus monotonicity give .
- Premise: . Assumption: . Both trivial. Copy: accessibility.
- →E: cite and , consequences of . Every valuation satisfying makes both and true, hence . Likewise ∧I, ∧E, ∨I, ¬E ( and are not simultaneously true, so no valuation satisfies and follows trivially), ⊥E for the same reason, and ¬¬E because and have identical tables.
- ∨E: with , , and true, either or is true, so in either case is too.
- →I: line is and closes the box from lines to , with and . That box is open at line , so , and induction gives . By semantic deduction, . ¬I is the same with : if , no valuation of makes true, so all make true.
At the last line no box is open, , and the invariant says .
∎→I is the only delicate case and explains why discharge matters. If a line could cite assumption after its box closed, the invariant would break: that line would depend on , but . This is precisely the error the lab checker must detect, requested by the coding exercise.
Soundness has a practical consequence already seen: to show no need to test every derivation; one valuation making premises true and false suffices. Thus (with , ), and the system is consistent: , since no valuation makes true.
Proof
Sketch, Kalmár’s version. It suffices to consider : if , then by semantic deduction, and a derivation of that tautology yields one of from by applying →E times.
Let be a tautology with variables . For each valuation , write if and if , likewise for any formula : if and otherwise.
- Kalmár’s lemma: for every formula on those variables. Prove by induction on ‘s construction; each case is a small fixed derivation. For instance, if with and , from and derive by assuming , obtaining by →E and by ¬E, then closing with ¬I.
- Since is tautological, for all valuations: for all .
- Eliminate assumptions one by one. Combine two derivations differing only in versus using (excluded middle, needing the classical rule) and ∨E. After rounds remains.
Three caveats for specialists:
- Completeness does not mean short proofs. Kalmár’s is of order , like the truth table. Whether any propositional proof system has polynomial-size proofs for every tautology is an open problem equivalent to (Cook and Reckhow, 1979): the subject of proof complexity, and why proving a formula has no SAT solution can be very expensive.
- First order is also complete (Gödel, 1929): every first-order logical consequence has a derivation. But no truth table decides , and first-order consequence is undecidable: derivations can be enumerated, but if none exists the search does not terminate.
- Do not confuse completeness with Gödel’s incompleteness theorems (1931). These concern theories (axiom sets like arithmetic’s), not logical calculus: no consistent, recursively axiomatizable, sufficiently expressive theory proves all arithmetic truths.
Implementation: a proof checker
Write the core of a propositional proof assistant from scratch: a checker accepting or rejecting Fitch proofs line by line. The first cell is a compact version of the first lesson’s engine: tuple formulas, parser with standard precedence, minimal-parenthesis printer, and truth-table consequence.
import itertools, re
# Fórmulas como tuplas: ("var", "p"), ("bot",), ("not", A), ("and", A, B), ("or", A, B), ("imp", A, B)
BOT = ("bot",)
ALIAS = {"->": "→", "~": "¬", "&": "∧", "|": "∨"}
TOKEN = re.compile(r"\s*(->|→|¬|~|∧|&|∨|\||⊥|\(|\)|[a-z][a-z0-9]*)")
def parse(s):
"""Precedencia: ¬ > ∧ > ∨ > →. El condicional asocia por la derecha: p → q → r es p → (q → r)."""
toks, pos = [], 0
s = s.strip()
while pos < len(s):
m = TOKEN.match(s, pos)
if not m:
raise SyntaxError(f"no entiendo {s[pos:]!r}")
toks.append(ALIAS.get(m.group(1), m.group(1)))
pos = m.end()
toks.append(None)
i = 0
def peek():
return toks[i]
def eat(t=None):
nonlocal i
tok = toks[i]
if t is not None and tok != t:
raise SyntaxError(f"esperaba {t!r} y encontré {tok!r}")
i += 1
return tok
def imp():
a = disj()
if peek() == "→":
eat()
return ("imp", a, imp())
return a
def disj():
a = conj()
while peek() == "∨":
eat()
a = ("or", a, conj())
return a
def conj():
a = unary()
while peek() == "∧":
eat()
a = ("and", a, unary())
return a
def unary():
t = eat()
if t == "¬":
return ("not", unary())
if t == "⊥":
return BOT
if t == "(":
a = imp()
eat(")")
return a
if t and t[0].isalpha():
return ("var", t)
raise SyntaxError(f"fórmula incompleta en {s!r}")
f = imp()
if peek() is not None:
raise SyntaxError(f"sobra {peek()!r} en {s!r}")
return f
PREC = {"imp": 1, "or": 2, "and": 3}
SYM = {"imp": "→", "or": "∨", "and": "∧"}
def show(f, need=0):
"""Escribe f con los paréntesis mínimos (need: precedencia mínima que el contexto admite sin paréntesis)."""
k = f[0]
if k == "var":
return f[1]
if k == "bot":
return "⊥"
if k == "not":
return "¬" + show(f[1], 4)
p = PREC[k]
s = f"{show(f[1], p + 1)} {SYM[k]} {show(f[2], p if k == 'imp' else p + 1)}"
return f"({s})" if p < need else s
def variables(f, acc=None):
acc = set() if acc is None else acc
if f[0] == "var":
acc.add(f[1])
for g in f[1:]:
if isinstance(g, tuple):
variables(g, acc)
return acc
def value(f, v):
"""Semántica veritativa: v asigna True/False a cada variable."""
k = f[0]
if k == "var":
return v[f[1]]
if k == "bot":
return False
if k == "not":
return not value(f[1], v)
a, b = value(f[1], v), value(f[2], v)
return {"and": a and b, "or": a or b, "imp": (not a) or b}[k]
def entails(premises, phi):
"""Γ ⊨ φ por tabla de verdad. Devuelve (True, None) o (False, valoración que lo refuta)."""
names = sorted(set().union(variables(phi), *[variables(g) for g in premises]))
for bits in itertools.product([False, True], repeat=len(names)):
v = dict(zip(names, bits))
if all(value(g, v) for g in premises) and not value(phi, v):
return False, {x: int(b) for x, b in v.items()}
return True, None
for s in ["p -> q -> r", "(p -> q) -> r", "~(p | q) -> ~p & ~q", "p & (q & r)", "¬¬p ∨ ⊥"]:
print(f"{s:22s} -> {show(parse(s))}")
print(entails([parse("p -> q"), parse("~q")], parse("~p")))
print(entails([parse("p -> q"), parse("q")], parse("p")))The last two lines are modus tollens, valid, and affirming the consequent, invalid: the table returns countermodel , .
Now the checker. A proof is a list of lines (fórmula, regla, *citas), numbered from 1. Class Fitch maintains the open-box stack and closed-box list; get checks scope, rejecting citations of closed-box lines; each rule checks its schema before modifying anything and raises ProofError with an explanation on failure. innermost requires a box rule to cite the innermost box ending immediately before; discharge closes it.
class ProofError(Exception):
pass
class Fitch:
"""Demostración al estilo Fitch que se comprueba línea a línea (las líneas se numeran desde 1)."""
def __init__(self, premises=()):
self.premises = [parse(p) if isinstance(p, str) else p for p in premises]
self.lines, self.just, self.depth = [], [], []
self.open = [] # pila de cajas abiertas: número de la línea de su suposición
self.closed = [] # cajas ya cerradas, como (i, j): sus líneas no se pueden volver a citar
def get(self, k):
"""Fórmula de la línea k, si es accesible desde la línea que se está escribiendo."""
n = len(self.lines) + 1
if not 1 <= k < n:
raise ProofError(f"cita la línea {k}, que no existe antes de la {n}")
for i, j in self.closed:
if i <= k <= j:
raise ProofError(f"cita la línea {k}, de la caja {i}..{j}, que ya está cerrada")
return self.lines[k - 1]
def innermost(self, i, j):
"""La caja citada debe ser la más interna y acabar justo en la línea anterior."""
n = len(self.lines) + 1
if not self.open:
raise ProofError("no hay ninguna caja abierta")
if (i, j) != (self.open[-1], n - 1):
raise ProofError(f"debe citar la caja más interna, {self.open[-1]}..{n - 1}")
return self.lines[i - 1], self.lines[j - 1]
def discharge(self):
"""Cierra la caja más interna: su suposición queda descargada."""
i = self.open.pop()
self.closed.append((i, len(self.lines)))
def add(self, f, rule, *refs):
f = parse(f) if isinstance(f, str) else f
if rule not in RULES:
raise ProofError(f"regla desconocida {rule!r}")
RULES[rule](self, f, *refs) # lanza ProofError si el paso no es válido
self.lines.append(f)
sep = "-" if rule in ("→I", "¬I") else ", " # las reglas de caja citan un rango i-j
self.just.append(rule + (" " + sep.join(map(str, refs)) if refs else ""))
self.depth.append(len(self.open))
def need(cond, msg):
if not cond:
raise ProofError(msg)
def r_premisa(P, f):
need(not P.open and f in P.premises, "no es una de las premisas (o está dentro de una caja)")
def r_sup(P, f):
P.open.append(len(P.lines) + 1) # abre una caja; su suposición es esta línea
def r_copia(P, f, a):
need(P.get(a) == f, "copia una fórmula distinta")
def r_and_i(P, f, a, b):
need(f == ("and", P.get(a), P.get(b)), "∧I: la conclusión debe ser (línea a) ∧ (línea b)")
def r_and_e(side):
def rule(P, f, a):
g = P.get(a)
need(g[0] == "and", f"∧E: la línea {a} no es una conjunción")
need(f == g[side], "∧E: la conclusión no es ese miembro de la conjunción")
return rule
def r_or_i(side):
def rule(P, f, a):
need(f[0] == "or" and f[side] == P.get(a), f"∨I: la conclusión debe ser una disyunción con la línea {a} como miembro")
return rule
def r_or_e(P, f, a, b, c):
d, g, h = P.get(a), P.get(b), P.get(c)
need(d[0] == "or", f"∨E: la línea {a} no es una disyunción")
need(g == ("imp", d[1], f) and h == ("imp", d[2], f), "∨E: hacen falta φ → χ y ψ → χ para cada miembro de φ ∨ ψ")
def r_imp_e(P, f, a, b):
g, h = P.get(a), P.get(b)
need(h[0] == "imp", f"→E: la línea {b} no es un condicional")
need(h[1] == g, f"→E: el antecedente de la línea {b} no es la línea {a}")
need(h[2] == f, "→E: la conclusión debe ser el consecuente")
def r_not_i(P, f, i, j):
phi, last = P.innermost(i, j)
need(last == BOT, "¬I: la caja tiene que terminar en ⊥")
need(f == ("not", phi), "¬I: la conclusión debe ser la negación de la suposición")
P.discharge()
def r_not_e(P, f, a, b):
need(f == BOT and P.get(b) == ("not", P.get(a)), "¬E: hacen falta φ y ¬φ, y se concluye ⊥")
def r_bot_e(P, f, a):
need(P.get(a) == BOT, f"⊥E: la línea {a} no es ⊥")
def r_dne(P, f, a):
need(P.get(a) == ("not", ("not", f)), "¬¬E: la línea citada debe ser ¬¬φ")
RULES = {"premisa": r_premisa, "sup": r_sup, "copia": r_copia,
"∧I": r_and_i, "∧E1": r_and_e(1), "∧E2": r_and_e(2), "∨I1": r_or_i(1), "∨I2": r_or_i(2), "∨E": r_or_e,
"→E": r_imp_e, "¬I": r_not_i, "¬E": r_not_e, "⊥E": r_bot_e, "¬¬E": r_dne}
def check(proof, premises=(), goal=None):
"""Comprueba una demostración entera. Devuelve (True, P) o (False, mensaje con la línea que falla)."""
P = Fitch(premises)
for n, (f, rule, *refs) in enumerate(proof, start=1):
try:
P.add(f, rule, *refs)
except ProofError as e:
return False, f"línea {n} ({show(parse(f) if isinstance(f, str) else f)}): {e}"
if P.open:
return False, f"quedan suposiciones abiertas en las líneas {P.open}"
if goal is not None and (not P.lines or P.lines[-1] != parse(goal)):
return False, "la última línea no es el objetivo"
return True, P
def show_proof(P):
for n, (f, j, d) in enumerate(zip(P.lines, P.just, P.depth), start=1):
print(f"{n:>3} {'│ ' * d}{show(f):<{24 - 2 * d}} {j}")→I is missing. It is the most important rule and you implement it in the coding exercise; here a hidden cell loads it so the rest works. With the complete checker, check the builder’s three derivations and three flawed proofs.
contrarreciproco = [
("p -> q", "sup"),
("~q", "sup"),
("p", "sup"),
("q", "→E", 3, 1),
("⊥", "¬E", 4, 2),
("~p", "¬I", 3, 5),
("~q -> ~p", "→I", 2, 6),
("(p -> q) -> (~q -> ~p)", "→I", 1, 7),
]
de_morgan = [ # ¬p ∧ ¬q ⊢ ¬(p ∨ q)
("~p & ~q", "premisa"),
("p | q", "sup"),
("p", "sup"),
("~p", "∧E1", 1),
("⊥", "¬E", 3, 4),
("p -> ⊥", "→I", 3, 5),
("q", "sup"),
("~q", "∧E2", 1),
("⊥", "¬E", 7, 8),
("q -> ⊥", "→I", 7, 9),
("⊥", "∨E", 2, 6, 10),
("~(p | q)", "¬I", 2, 11),
]
tercero_excluido = [ # ⊢ p ∨ ¬p, que necesita la regla clásica ¬¬E
("~(p | ~p)", "sup"),
("p", "sup"),
("p | ~p", "∨I1", 2),
("⊥", "¬E", 3, 1),
("~p", "¬I", 2, 4),
("p | ~p", "∨I2", 5),
("⊥", "¬E", 6, 1),
("~~(p | ~p)", "¬I", 1, 7),
("p | ~p", "¬¬E", 8),
]
casos = [
("contrarrecíproco", contrarreciproco, [], "(p -> q) -> (~q -> ~p)"),
("De Morgan", de_morgan, ["~p & ~q"], "~(p | q)"),
("tercero excluido", tercero_excluido, [], "p | ~p"),
]
for nombre, prueba, prem, goal in casos:
ok, P = check(prueba, prem, goal)
print(f"── {nombre}: {'correcta' if ok else P}")
show_proof(check(contrarreciproco, [], None)[1])
print("\nTres demostraciones defectuosas:")
afirmar_consecuente = [("p -> q", "premisa"), ("q", "premisa"), ("p", "→E", 2, 1)]
fuera_de_la_caja = [("q", "sup"), ("q -> q", "→I", 1, 1), ("q", "copia", 1)]
caja_sin_cerrar = [("p", "sup"), ("p | q", "∨I1", 1)]
for prueba, prem in [(afirmar_consecuente, ["p -> q", "q"]), (fuera_de_la_caja, []), (caja_sin_cerrar, [])]:
print(" ", check(prueba, prem)[1])The flawed proofs fail differently: the first affirms the consequent (from and one cannot infer ); the second uses assumption after discharge and would otherwise “prove” without premises; the third leaves an assumption open, proving , not .
Soundness checked empirically
Soundness says each line follows logically from premises and assumptions open at that point. Using the first cell’s semantic engine, audit accepted proofs line by line. To avoid relying on a few handwritten proofs, generate thousands randomly: a generator proposes random steps and the checker decides which remain. If a checker bug admits an invalid step, the audit finds a countermodel.
import random
def audit(P):
"""Corrección línea a línea: premisas + suposiciones abiertas en la línea n ⊨ fórmula de la línea n."""
stack, bad = [], []
for n, (f, j) in enumerate(zip(P.lines, P.just), start=1):
rule = j.split()[0]
if rule in ("→I", "¬I"):
stack.pop() # esta línea ya está fuera de la caja
if rule == "sup":
stack.append(f)
ok, v = entails(P.premises + stack, f)
if not ok:
bad.append((n, show(f), v))
return bad
for nombre, prueba, prem, goal in casos:
print(f"{nombre:17s} líneas con Γ + abiertas ⊭ línea: {audit(check(prueba, prem, goal)[1])}")
ATOMS = [parse(x) for x in ["p", "q", "r", "~p", "p -> q", "q | r", "~(p & q)", "⊥"]]
def random_proof(rnd, steps=14):
"""Genera una demostración al azar: propone pasos y se queda con los que el verificador acepta."""
P = Fitch(rnd.sample(ATOMS[:7], 2))
for g in P.premises:
P.add(g, "premisa")
for _ in range(steps):
n = len(P.lines)
acc = [k for k in range(1, n + 1) if not any(i <= k <= j for i, j in P.closed)]
a, b, c = (rnd.choice(acc) for _ in range(3))
fa, fb = P.lines[a - 1], P.lines[b - 1]
r = rnd.choice(["sup", "sup", "→I", "¬I", "∧I", "∧E1", "∧E2", "∨I1", "∨I2", "→E", "¬E", "⊥E", "¬¬E", "∨E"])
try:
if r == "sup":
P.add(rnd.choice(ATOMS), "sup")
elif r in ("→I", "¬I") and P.open:
i = P.open[-1]
f = ("imp", P.lines[i - 1], P.lines[-1]) if r == "→I" else ("not", P.lines[i - 1])
P.add(f, r, i, n)
elif r == "∧I":
P.add(("and", fa, fb), r, a, b)
elif r in ("∧E1", "∧E2") and fa[0] == "and":
P.add(fa[1 if r == "∧E1" else 2], r, a)
elif r in ("∨I1", "∨I2"):
o = rnd.choice(ATOMS)
P.add(("or", fa, o) if r == "∨I1" else ("or", o, fa), r, a)
elif r == "→E" and fb[0] == "imp":
P.add(fb[2], r, a, b)
elif r == "¬E":
P.add(BOT, r, a, b)
elif r == "⊥E":
P.add(rnd.choice(ATOMS), r, a)
elif r == "¬¬E" and fa[0] == "not" and fa[1][0] == "not":
P.add(fa[1][1], r, a)
elif r == "∨E" and fa[0] == "or" and fb[0] == "imp":
P.add(fb[2], r, a, b, c)
except ProofError:
pass # paso rechazado: se descarta
return P
def fuzz(n_proofs=1500, seed=0):
rnd = random.Random(seed)
lines = 0
for _ in range(n_proofs):
P = random_proof(rnd)
lines += len(P.lines)
bad = audit(P)
if bad:
return lines, bad[0], P
return lines, None, None
lines, bad, _ = fuzz()
print(f"\nCorrección empírica: {lines} líneas de 1500 demostraciones aleatorias, contraejemplos: {bad}")
# Un verificador con un fallo: →I que no descarga la suposición
def imp_i_sin_descarga(P, f, i, j):
phi, psi = P.innermost(i, j)
need(f == ("imp", phi, psi), "→I: conclusión incorrecta")
P.open.pop() # cierra la caja... pero no la marca como cerrada
RULES["→I"], correcta = imp_i_sin_descarga, RULES["→I"]
ok, P = check(fuera_de_la_caja, [], "q")
print("\nCon el fallo, «⊢ q» se acepta:", ok, "| auditoría:", audit(P) if ok else P)
lines, bad, P = fuzz()
print(f"El fuzzing lo encuentra tras {lines} líneas: línea {bad[0]}, {bad[1]}, valoración {bad[2]}")
RULES["→I"] = correctaWith the correct checker over eleven thousand generated lines pass audit: each follows from its premises and open assumptions, the soundness invariant checked in thousands of instances. Then introduce a subtle realistic bug: →I pops the box stack but does not mark the box closed, leaving lines citable. The faulty checker accepts , and the audit points to the line following from nothing ( false under ). The random generator finds its own counterexample in a few dozen lines. The practical lesson: a faulty checker is exposed not by good proofs but bad ones it accepts, hence testing against semantics.
The professional version: solvers and proof assistants
To decide in practice, do not write truth tables: ask a solver whether is satisfiable, and consequence holds exactly when it is not. SymPy provides this (entails), converting to conjunctive normal form and using a DPLL-like algorithm. Check agreement with our table on random formulas.
import sympy as sp
from sympy.logic.inference import entails as sp_entails, satisfiable
def to_sympy(f, env):
k = f[0]
if k == "var":
return env.setdefault(f[1], sp.Symbol(f[1]))
if k == "bot":
return sp.false
if k == "not":
return sp.Not(to_sympy(f[1], env))
a, b = to_sympy(f[1], env), to_sympy(f[2], env)
return {"and": sp.And, "or": sp.Or, "imp": sp.Implies}[k](a, b)
env = {}
gamma = [to_sympy(parse(s), env) for s in ["p -> q", "q -> r"]]
print("sympy: {p → q, q → r} ⊨ p → r:", sp_entails(to_sympy(parse("p -> r"), env), gamma))
print("contramodelo de q → p desde p → q:", satisfiable(sp.And(gamma[0], sp.Not(to_sympy(parse("q -> p"), env)))))
def random_formula(rnd, depth):
if depth == 0 or rnd.random() < 0.25:
return rnd.choice([("var", "p"), ("var", "q"), ("var", "r"), BOT])
k = rnd.choice(["not", "and", "or", "imp"])
if k == "not":
return ("not", random_formula(rnd, depth - 1))
return (k, random_formula(rnd, depth - 1), random_formula(rnd, depth - 1))
rnd = random.Random(1)
acuerdos, validas, N = 0, 0, 150
for _ in range(N):
prem = [random_formula(rnd, 2) for _ in range(2)]
phi = random_formula(rnd, 3)
ours = entails(prem, phi)[0]
theirs = bool(sp_entails(to_sympy(phi, env), [to_sympy(g, env) for g in prem]))
acuerdos += ours == theirs
validas += ours
print(f"tabla de verdad frente a sympy: {acuerdos}/{N} coinciden ({validas} consecuencias válidas)")SymPy answers , not : it says whether consequence holds but supplies no independently checkable derivation. A SAT solver reporting “unsatisfiable” can instead produce a checkable certificate, the idea of resolution. For the derivation itself use a proof assistant. In Lean 4 contraposition is written:
example (p q : Prop) : (p → q) → (¬q → ¬p) := by
intro hpq hnq hp -- tres suposiciones: tres →I (las cajas 1, 2 y 3)
exact hnq (hpq hp) -- hpq hp : q por →E; hnq aplicado a q da False (¬E)
Each tactic is a table rule. intro opens an assumption discharged at the end (→I and ¬I, because in Lean is defined as ); applying a function to an argument is →E. Lean’s state between tactics is the first interactive’s hypothesis–goal panel. The design matches our lab: a small kernel checks proof terms, so trusting a thousand-line proof requires trusting only that kernel, not the tactics that generated it. This is developed in proof assistants, and enables a language model to propose proofs: the checker decides.
Common mistakes
Exercises
Step 1 of 3. Which strategy and assumption do you choose?
Step 1 of 3. What is the most economical case split?
Step 1 of 4. Begin as with . What equation do you obtain?
Step 1 of 4. What strategy does the form of the goal dictate?
Step 1 of 3. The goal is a negation. What do you do?
r_imp_i(P, f, i, j) in this reduced checker (rules: premise, sup, copy, →E and →I). At line n = len(P.lines) + 1, →I cites the box from lines i to j. Check that there is an open box, that the innermost begins at i (P.open[-1] == i) and ends immediately before (j == n - 1), and that f == imp(línea i, línea j); if anything fails, raise ProofError. If all is correct, discharge the assumption: remove the box from P.open and add (i, j) to P.closed so its lines cannot be cited again. Formulas are tuples: ('var', 'p'), imp(a, b) = ('imp', a, b).class ProofError(Exception):
pass
def imp(a, b):
return ("imp", a, b)
class Fitch:
def __init__(self, premises=()):
self.premises = list(premises)
self.lines = [] # fórmulas, línea n en self.lines[n - 1]
self.open = [] # pila de cajas abiertas: número de línea de cada suposición
self.closed = [] # cajas cerradas (i, j): sus líneas ya no se pueden citar
def get(self, k):
n = len(self.lines) + 1
if not 1 <= k < n:
raise ProofError(f"la línea {k} no existe antes de la {n}")
for i, j in self.closed:
if i <= k <= j:
raise ProofError(f"la línea {k} está en la caja cerrada {i}..{j}")
return self.lines[k - 1]
def add(self, f, rule, *refs):
RULES[rule](self, f, *refs)
self.lines.append(f)
def r_premisa(P, f):
if P.open or f not in P.premises:
raise ProofError("no es una premisa")
def r_sup(P, f):
P.open.append(len(P.lines) + 1)
def r_copia(P, f, a):
if P.get(a) != f:
raise ProofError("copia una fórmula distinta")
def r_imp_e(P, f, a, b):
if P.get(b) != imp(P.get(a), f):
raise ProofError("→E mal aplicada")
def r_imp_i(P, f, i, j):
"""→I en la línea n = len(P.lines) + 1, citando la caja i..j.
Comprueba que (i, j) es la caja más interna y abierta, que termina justo antes (j = n - 1)
y que f es imp(línea i, línea j); si algo falla, lanza ProofError. Después, descarga la suposición."""
pass
RULES = {"premisa": r_premisa, "sup": r_sup, "copia": r_copia, "→E": r_imp_e, "→I": r_imp_i}
def check(proof, premises=()):
"""True si la demostración es correcta y no deja suposiciones abiertas."""
P = Fitch(premises)
try:
for f, rule, *refs in proof:
P.add(f, rule, *refs)
except ProofError:
return False
return not P.openMore than one answer may be correct.
Summary
- Strategies by form: prove by assuming (directly) or (contraposition); by assuming and reaching ; by fixing an arbitrary object; by giving a witness. An assumption gives a new name, and a requires reasoning by exhaustive cases.
- Contradiction versus contraposition: negation introduction (refutation) is intuitionistic; concluding from is classical. If the contradiction consists of deriving from alone to clash with assumption , you have a contrapositive proof.
- Existence: a constructive proof gives a witness and therefore an algorithm; a nonconstructive one (by cases on an undecided claim or by contradiction) may not. is the canonical example.
- Counterexamples: one suffices to refute a ; no finite number of cases proves it ( fails at , has factor , the circle gives ).
- Natural deduction: boxes are scopes; a line in a closed box cannot be cited. The Fitch checker fits in a few dozen lines and is audited against the semantics.
- Soundness and completeness: implies (induction on the derivation, using the deduction theorem in the →I step), and implies (Kalmár). A countermodel suffices to refute derivability; the existence of a proof does not mean it is short.