The whole proof in tactics#
Winker’s condition is only half of the way. To derive from the three laws A1, A2, R Huntington’s equation
and with it a Boolean algebra, three more stages are needed. In this part we put the whole proof together — following Mann’s plan and the formalization in mathlib — and measure how much it weighs.
Stage |
What it proves |
In mathlib |
Here |
|---|---|---|---|
1 |
Winker’s condition \(q + 2a = 2a\) |
|
12 theorems, |
2 |
lemmas with hypotheses |
|
|
3 |
from \(A + B = B\) an element \(e\) with \(e + e = e\) |
|
|
4 |
from \(e + e = e\) a zero, \(n(n(x)) = x\), Huntington’s equation |
|
|
5 |
the sections used for the real terms |
— |
|
Stages 2–5 need two ideas that were not in part 1: lemmas with hypotheses and abbreviations for long terms. Both are forms of compression.
Lemmas with hypotheses#
Mann’s lemma 35 says: if \(n(a + n(b)) = c\), then \(n(n(a + b) + c) = a\). In Lean this is a function: it takes a proof of the hypothesis and returns a proof of the conclusion. Our kernel has no implication — it knows only equations with variables. We manage like this:
we prove the lemma once, in a separate kernel in which \(a, b, c\) are constants and the hypothesis is an axiom
h1;to use it for concrete terms and a proof of the hypothesis, we substitute them into that one proof: the constants are replaced by terms, and every use of the axiom
h1— by the proof of the hypothesis (the functiontransport);the kernel checks the result from scratch, like any other proof.
from robbins import theory, Hypothetical, Goal, nodes
from robbins_proof import winker_by_hand
from syntax import show_equation
K = theory()
M35 = Hypothetical(K, "mann_35", "abc", ["n(a + n(b)) = c"], "n(n(a + b) + c) = a",
lambda g: (g.rw("← h1"), g.rw("R a b")))
print("proof with constants — nodes:", nodes(M35.proof))
# use: a := x + y, b := y, c := n(x + y + n(y)); the hypothesis is then plain reflexivity
hypothesis_proof = Goal(K, "n(x + y + n(y)) = n(x + y + n(y))").rfl().qed()
proof = M35({"a": "x + y", "b": "y", "c": "n(x + y + n(y))"}, hypothesis_proof)
print("kernel:", show_equation(K.conclusion(proof)))
proof with constants — nodes: 5
kernel: n(n(x + y + y) + n(x + y + n(y))) = x + y
Mathlib proves lemma 36 by induction on \(k\) (for every \(k \ge 1\)). Our kernel knows no induction, but further on only \(k = 1, 2, 3\) are needed — so we unroll the induction: the proof for \(k\) uses the proof for \(k - 1\) as the hypothesis of lemma 35. This is an ordinary loop in Python:
import inspect
from robbins_proof import hypothetical_lemmas
source = inspect.getsource(hypothetical_lemmas)
print(source[source.index(" def lemma_36"):source.index(" c = ")])
def lemma_36(k):
def script(g):
ih = h if k == 1 else M[36, k - 1](
{"a": "a", "b": "b", "c": "c"}, h)
b = "b" if k == 1 else f"b + {times(k - 1, 'a + c')}"
g.have("m35", M[35]({"a": "a", "b": b, "c": "c"}, ih))
g.nth_rw(1, "← m35")
g.rw(f"← R c (a + {b})", side="rhs")
g.ac()
return H(f"mann_36_{k}", "abc", ["n(a + n(b)) = c"],
f"n(a + n(b + {times(k, 'a + c')})) = c", script)
Such a lemma is a compressed fragment of a proof: it stands in the script once, and in the proof object it appears as many times as it is used. Lean pays less: its kernel knows implication, so a lemma with hypotheses is a constant that is checked once, and every use is one application of a function. Our kernel checks every copy separately.
Abbreviations for long terms: sections#
In stage 3 the pair \(A + B = B\) gives an element \(e\) with \(e + e = e\):
Stage 1 gives such a pair for \(A = q = n(n(3a) + a)\) and \(B = 2a\). Let us substitute it and look at \(e\):
from robbins_proof import E, Q
from syntax import term, show
from kernel import subst
from ac import symbols
e_real = subst(term(E), {"A": term(Q), "B": term("a + a")})
print(f"e with constants A, B: {symbols(term(E))} symbols")
print(f"e for A = q, B = 2a: {symbols(e_real)} symbols")
print(show(e_real)[:300], "…")
e with constants A, B: 131 symbols
e for A = q, B = 2a: 329 symbols
a + a + (n(n(n(a + a + a) + a) + n(a + a)) + n(n(n(a + a + a) + a) + n(a + a))) + n(a + a + (n(n(n(a + a + a) + a) + n(a + a)) + n(n(n(a + a + a) + a) + n(a + a))) + n(a + a + (n(n(n(a + a + a) + a) + n(a + a)) + n(n(n(a + a + a) + a) + n(a + a))))) + (a + a + (n(n(n(a + a + a) + a) + n(a + a)) + n( …
Nobody writes such terms in a proof. In Lean, mathlib introduces names: obtain ⟨a, b, h⟩ := winker gives constants
\(a, b\) with the hypothesis \(a + b = b\), and set d := … — an abbreviation. Our counterpart is a section (class
Section): a group of lemmas about constants that satisfy hypotheses. We prove the lemmas of a section with short
constants, and then the method use writes all of them down again — with the constants replaced by the real terms.
This is the whole proof:
from robbins_proof import robbins_theorem
print(inspect.getsource(robbins_theorem))
def robbins_theorem(by_auto=False):
"""All stages; returns the kernel with every theorem of the proof."""
K = theory()
(winker_by_auto if by_auto else winker_by_hand)(K)
M = hypothetical_lemmas(K)
WS = idempotent_section(K, M)
ES = huntington_section(K)
ES.use(WS, {"e": E}, Inst("idem", ())) # e := 3d over A, B
WS.use(K, {"A": Q, "B": "a + a"}, Inst("winker", ("a",)))
return K
Let us run it stage by stage and measure the time:
import time
from kernel import Inst
from robbins_proof import idempotent_section, huntington_section
timings = {}
start = time.perf_counter()
K = theory()
winker_by_hand(K)
timings["1. Winker's condition"] = time.perf_counter() - start
start = time.perf_counter()
M = hypothetical_lemmas(K)
timings["2. lemmas with hypotheses"] = time.perf_counter() - start
start = time.perf_counter()
WS = idempotent_section(K, M)
ES = huntington_section(K)
timings["3–4. sections with constants"] = time.perf_counter() - start
start = time.perf_counter()
ES.use(WS, {"e": E}, Inst("idem", ()))
WS.use(K, {"A": Q, "B": "a + a"}, Inst("winker", ("a",)))
timings["5. sections used"] = time.perf_counter() - start
for stage, seconds in timings.items():
print(f"{stage:26} {seconds:6.2f} s")
print()
print("theorem: ", show_equation(K.facts["huntington"][1:]))
print("assumptions:", sorted(K.assumptions["huntington"]))
1. Winker's condition 0.06 s
2. lemmas with hypotheses 0.40 s
3–4. sections with constants 0.97 s
5. sections used 1.63 s
theorem: n(n(x) + n(y)) + n(n(x) + y) = x
assumptions: ['A1', 'A2', 'R']
The kernel accepted Huntington’s equation, and the only assumptions the proof uses are A1, A2 and R. The whole proof, from the Robbins equation to Huntington’s equation, was checked by our kernel from lecture 3 in a few seconds.
Abbreviations have their price only when written out: stage 5 writes the lemmas down again with long terms. Let us count the “mass” of a proof — the total number of symbols in all terms written down in the proof object. We compare the lemmas of section ES (the zero, \(n(n(x)) = x\), Huntington’s equation and the auxiliary lemmas) in two versions: with the constant \(e\) and with the real \(e\) of 329 symbols substituted.
from kernel import Refl, Symm, Trans, CongrArg
def masa(proof):
"""The number of symbols in all terms written down in a proof."""
stack, sum_term = [proof], 0
while stack:
d = stack.pop()
if isinstance(d, Refl):
sum_term += symbols(d.t)
elif isinstance(d, Inst):
sum_term += sum(symbols(a) for a in d.args)
elif isinstance(d, CongrArg):
sum_term += symbols(d.C)
stack.append(d.p)
elif isinstance(d, Symm):
stack.append(d.p)
else:
stack += [d.p, d.q]
return sum_term
es_names = [name for name, *_ in ES.lemmas]
for where, kernel_ in [("with constant e", ES.kernel), ("with the real e", K)]:
w = sum(nodes(kernel_.proofs[n]) for n in es_names)
m = sum(masa(kernel_.proofs[n]) for n in es_names)
print(f"{len(es_names)} lemmas {where:16} nodes {w:5}, symbols in terms {m:8,}".replace(",", " "))
15 lemmas with constant e nodes 341 symbols in terms 1 394
15 lemmas with the real e nodes 341 symbols in terms 116 873
The number of nodes does not change — it is the same proof. Only what is written in it grows: every \(e\) becomes a long
term, and there are dozens of times more symbols. If we wrote the proof with the real terms from the start, the
tactics would sort sums of more than a dozen summands, and the proof itself — not only its notation — would be much
bigger. An abbreviation (a section in our code, set and obtain in Lean) is compression of terms, just as
a lemma is compression of proofs.
How much a proof weighs#
Now we can measure the whole proof in three ways:
the script — what we write: the lines of the module
robbins_proof(without comments and descriptions);the proof object — what the kernel checks: the nodes of the proofs of all theorems that Huntington’s equation uses; a use of a lemma is one
Instnode;the tree without lemmas — the same proof if every use of a lemma were replaced by its proof, and so on, until only axioms remain (the function
expandedcounts this exactly, without building the tree).
import io
import tokenize
import robbins_proof
from robbins import lemmas_used, expanded
def code_lines(module):
"""Lines with code: without empty lines, comments and docstrings."""
content = inspect.getsource(module)
docs = set()
previous = None
for t in tokenize.generate_tokens(io.StringIO(content).readline):
if t.type == tokenize.STRING and previous in (tokenize.INDENT, tokenize.NEWLINE, None):
docs.update(range(t.start[0], t.end[0] + 1))
if t.type not in (tokenize.NL, tokenize.COMMENT):
previous = t.type
return sum(1 for i, w in enumerate(content.splitlines(), 1)
if w.strip() and not w.strip().startswith("#") and i not in docs)
used = lemmas_used(K, "huntington") | {"huntington"}
script = code_lines(robbins_proof)
obj = sum(nodes(K.proofs[n]) for n in used)
tree = expanded(K, K.proofs["huntington"])
print(f"script: {script:>15,} lines".replace(",", " "))
print(f"proof object: {obj:>15,} nodes in {len(used)} theorems".replace(",", " "))
print(f"tree without lemmas: {tree:>15,} nodes".replace(",", " "))
print(f"lemmas compress {tree / obj:,.0f} times; tactics {obj / script:,.0f} times".replace(",", " "))
script: 250 lines
proof object: 22 178 nodes in 34 theorems
tree without lemmas: 517 110 842 nodes
lemmas compress 23 316 times; tactics 89 times
More than half a billion nodes in the tree without lemmas — tens of thousands of times more than in the object the kernel really checks. A lemma used many times, inside other lemmas used many times, multiplies in the tree as in exponentiation. The second level of compression are tactics: every line of the script stands on average for several dozen nodes of the proof object.
By hand or with auto?#
The same proof can be assembled with stage 1 written by the tactic auto (part 2). Let us compare:
for by_auto in (False, True):
start = time.perf_counter()
K2 = robbins_theorem(by_auto=by_auto)
seconds = time.perf_counter() - start
used2 = lemmas_used(K2, "huntington") | {"huntington"}
print(f"by_auto={by_auto!s:5} {seconds:5.2f} s, object {sum(nodes(K2.proofs[n]) for n in used2):6} nodes, "
f"assumptions {sorted(K2.assumptions['huntington'])}")
by_auto=False 3.05 s, object 22178 nodes, assumptions ['A1', 'A2', 'R']
by_auto=True 7.20 s, object 22090 nodes, assumptions ['A1', 'A2', 'R']
The result is the same, the proof object similar, and the script of stage 1 contains not a single hint about where and with what to expand. This is the third kind of compression: search replaces creative decisions — but only where there are few of them.
What next: from Huntington to Boolean algebra#
Huntington’s equation together with A1 and A2 is one more set of axioms for Boolean algebra (E. V. Huntington, 1933).
In mathlib the last lines of the file Robbins.lean build from it a full instance BooleanAlgebra: zero, one, the
product \(x \cdot y = n(n(x) + n(y))\) and the distributive laws. In our course Huntington’s axioms of 1904, H1–H8, and
their consequences are in Tactics: from pattern to proof and in the Boole Lab library; associativity from H1–H8 — in
Associativity from Huntington’s axioms. Joining these two roads is a good exercise (see Scenarios: building tactics).