Tactics that compress#

In the previous part the script of the proof of lemma mann_44 had three tactics, and the proof checked by the kernel had 48 nodes. A tactic is a program that writes a proof for us. A good tactic turns a long, repetitive fragment of a proof into one word in the script — and this is the compression this chapter is about. The kernel still receives the whole proof, so the tactic need not be trusted: if it makes a mistake, the kernel rejects the result.

For the Robbins proof we build four tactics, from the simplest to the cleverest:

Tactic

What it does

Kind

ac

closes a goal whose sides differ only by the order and brackets of sums

decision procedure: always terminates, never guesses

rw_ac

rewrites with an equation whose left side sits in the goal “mixed up”

matching modulo A1, A2

ac_simp

rewrites with the given equations as long as possible, then ac

simplification to the end

auto

finds the creative expansions with the Robbins equation by itself

bounded search

The tactic ac: a normal form with a proof#

Two terms are equal by commutativity A1 and associativity A2 exactly when they have the same summands, counted with multiplicity — inside every sum, also deep under \(n(\ldots)\). This is easy to check: in every sum we sort the summands in a fixed order and group them to the left. The result is the normal form:

from syntax import term, show
from ac import normal

for text in ["(b + a) + (c + a)", "a + (a + (c + b))", "n(b + a) + n(a + n(b + a))"]:
    print(f"{text:28} ->  {show(normal(term(text)))}")
(b + a) + (c + a)            ->  a + a + b + c
a + (a + (c + b))            ->  a + a + b + c
n(b + a) + n(a + n(b + a))   ->  n(a + b) + n(a + n(a + b))

Sorting alone is not a proof, though. The tactic ac sorts so that every move can be written down with kernel rules: it merges two sorted sums into one, and then puts every summand in its place by swapping neighbours (insertion sort). One swap of neighbours is three steps: A2, then A1 inside, then A2 backwards.

import inspect
import ac

print(inspect.getsource(ac._insert))
def _insert(steps, path, comm, assoc):
    """P + x  with P a sorted chain: move x left to its place (insertion
    sort; one swap of neighbours = A2, then A1, then A2 backwards)."""
    P, x = at(steps.now, path)[1:]
    if not is_sum(P):
        if order_key(x) < order_key(P):
            steps.fact(path, comm, (P, x))            # P + x = x + P
        return
    P1, y = P[1], P[2]
    if order_key(x) >= order_key(y):
        return
    steps.fact(path, assoc, (P1, y, x))               # (P1 + y) + x
    steps.fact(path + (2,), comm, (y, x))             # = P1 + (y + x)
    steps.fact(path, assoc, (P1, x, y), backward=True)  # = (P1 + x) + y
    _insert(steps, path + (1,), comm, assoc)

Every steps.fact(...) adds to the proof an instance of an axiom put into the whole term by CongrArg. Let us look at the successive terms in a short example:

from robbins import theory
from ac import Steps, ac_proof

K = theory()                      # a kernel with the axioms A1, A2, R
steps = Steps(K, term("c + (b + a)"))
ac._sort(steps, (), "A1", "A2")
print(show(steps.start))
for bit in steps.pieces:
    print("  =", show(K.conclusion(bit)[1]))
print("rewrites:", steps.count)
c + (b + a)
  = c + (a + b)
  = c + a + b
  = a + c + b
  = a + (c + b)
  = a + (b + c)
  = a + b + c
rewrites: 6

Every line is the whole term after one rewrite: CongrArg puts the change of a subterm into the whole. The kernel gets one proof out of it — the rewrites joined by Trans. How much does such bookkeeping cost? Let us count the nodes of the proof for a sum of \(k\) different summands written in reverse order — the worst case of insertion sort:

from robbins import nodes

letters = "abcdefghijkl"
cost = {}
for k in range(2, 11):
    backwards = " + ".join(reversed(letters[:k]))
    in_order = " + ".join(letters[:k])
    proof = ac_proof(K, term(backwards), term(in_order))
    assert K.conclusion(proof) == (term(backwards), term(in_order))
    cost[k] = nodes(proof)
    print(f"k = {k:2}: {cost[k]:4} nodes, per pair of summands {cost[k] / (k * (k - 1) / 2):.1f}")
k =  2:    1 nodes, per pair of summands 1.0
k =  3:   13 nodes, per pair of summands 4.3
k =  4:   36 nodes, per pair of summands 6.0
k =  5:   69 nodes, per pair of summands 6.9
k =  6:  112 nodes, per pair of summands 7.5
k =  7:  165 nodes, per pair of summands 7.9
k =  8:  228 nodes, per pair of summands 8.1
k =  9:  301 nodes, per pair of summands 8.4
k = 10:  384 nodes, per pair of summands 8.5

The cost grows like \(k^2\): each of the \(k(k-1)/2\) pairs of summands has to be swapped, every swap is three rewrites, and every rewrite is three nodes in the proof (Inst, CongrArg, Trans) — hence the number of nodes per pair, which approaches 9. The script, on the other hand, always has one word: ac. The longer the sums, the bigger the compression.

Is ac correct? We do not have to prove it. If the tactic has a bug, the kernel rejects its proof. If the normal forms of the two sides differ, the tactic fails — rightly so, because then the equation does not follow from A1 and A2. Let us also test the tactic on random pairs of terms that are equal up to order and brackets:

import random

def random_term(rng, depth):
    if depth == 0 or rng.random() < 0.3:
        return rng.choice("abcd")
    if rng.random() < 0.25:
        return ("n", random_term(rng, depth - 1))
    return ("+", random_term(rng, depth - 1), random_term(rng, depth - 1))

def shuffled(rng, t):
    """The same term up to A1, A2: summands shuffled, brackets at random."""
    if isinstance(t, str):
        return t
    if t[0] == "n":
        return ("n", shuffled(rng, t[1]))
    parts = [shuffled(rng, s) for s in ac.addends(t)]
    rng.shuffle(parts)
    while len(parts) > 1:
        i = rng.randrange(len(parts) - 1)
        parts[i:i + 2] = [("+", parts[i], parts[i + 1])]
    return parts[0]

rng = random.Random(2026)
pairs = [(t, shuffled(rng, t)) for t in (random_term(rng, 6) for _ in range(500))]
accepted = sum(K.conclusion(ac_proof(K, s, t)) == (s, t) for s, t in pairs)
print(f"the kernel accepted {accepted} proofs out of {len(pairs)}")
the kernel accepted 500 proofs out of 500

Matching modulo associativity and commutativity#

An ordinary rw looks for a pattern literally. In the Robbins proof that is not enough: the left side of a lemma often sits in the goal in a different order or as a part of a longer sum. In mathlib this shows in lines such as rw [add_comm _ q, mann_47] — the summands have to be reordered by hand first, so that rw works at all.

The tactic rw_ac matches a pattern modulo A1 and A2. A variable of the pattern may then take several summands of a sum. For example, the left side of the Robbins equation matches this term in one way, with \(x = a + b\):

from ac import ac_match

pattern = term("n(n(x + y) + n(x + n(y)))")
t = normal(term("n(n(c + a + b) + n(b + a + n(c)))"))
for s in ac_match(pattern, t, {"x", "y"}, {}):
    print({x: show(v) for x, v in s.items()})
{'x': 'a + b', 'y': 'c'}

When the pattern fits a part of a sum, rw_ac first regroups the summands — the proof of the regrouping is written by ac — so that the matching fragment stands alone, and then rewrites it with an ordinary step. In the example the constants \(a, b, c, d\) satisfy the hypothesis \(a + b = c\), and in the goal \(a\) and \(b\) are separated by the summand \(d\):

from robbins import Goal, Section

K = theory()
S = Section(K, "abcd", ["a + b = c"])       # constants a, b, c, d and hypothesis h1: a + b = c
g = Goal(S.kernel, "n(b + (d + a)) = n(d + c)")
g.rw_ac("h1")
print(g)
g.ac()
print("nodes:", nodes(g.qed()))
n(d + c) = n(d + c)
nodes: 37

An ordinary rw [h1] would find nothing here: the tree of the term has no subtree \(a + b\). In the proof of lemma mann_48 the tactic rw_ac replaces in this way the manual add_comm _ q of mathlib.

ac_simp: rewrite as long as you can#

Mann’s lemmas with hypotheses (part 3) need several rewrites in different places on both sides. Instead of pointing to each, we give a list of equations, and ac_simp rewrites with them — each from left to right, modulo A1 and A2 — as long as one of them fits, and finally closes the goal with the tactic ac. A simple example: if \(e + e = e\) (an idempotent element), every sum made of copies of \(e\) and one \(x\) simplifies to \(e + x\).

S = Section(K, "e", ["e + e = e"])         # constant e and hypothesis h1: e + e = e
S.lemma("absorption", "e + (x + (e + e)) + e = x + e", lambda g: g.ac_simp("h1"))
print(show(S.kernel.facts["absorption"][1]), "=", show(S.kernel.facts["absorption"][2]),
      "| uses of h1 in the proof:", str(S.kernel.proofs["absorption"]).count("'h1'"))
e + (x + (e + e)) + e = x + e | uses of h1 in the proof: 3

The tactic replaced \(e + e\) by \(e\) three times, although the script never points to a place. Such simplification always ends when every rule shortens the term (here: two copies of \(e\) become one). When the rules do not shorten, ac_simp could go round in circles — that is why it has a limit on rewrites and fails with a message when it is exceeded, instead of running forever.

How to design a tactic#

These four examples show a few principles that fit every tactic — also the ones we compose in the Boole Lab and in the Tactic Lab (see Scenarios: building tactics):

  • Decide or fail fast. ac always terminates and never leaves a goal half done: either it closes it, or it reports an error. Such a tactic can safely be called at the end of every branch.

  • Have a measure of progress. ac_simp terminates because every good rule shortens the term; when the rules do not shorten, the limit saves us. In the Boole Lab the same role is played by the analysis “the sum of the sizes of the goals goes down”.

  • Bound the search. auto looks at only one step from each side and at a bounded pool of candidates. When the pool grows exponentially, a hint is better.

  • Do not ask for trust. Each of these tactics writes an ordinary proof made of five rules. The kernel checks it just like a proof typed by hand (the de Bruijn criterion, see Bound variables and de Bruijn indices).

  • Compress what repeats. In the Robbins proof the most frequent thing is the bookkeeping of associativity and commutativity — and this is exactly what ac swallows.

References and places worth a visit#

  • Lean 4: the tactic ac_rfl (in mathlib used with the type classes Std.Associative and Std.Commutative, see Archive/Robbins.lean); mathlib also has abel and ring, which bring expressions in abelian groups and rings to a normal form.

  • F. Baader, T. Nipkow, Term Rewriting and All That, Cambridge University Press (1998) — normal forms, rewriting modulo AC and its termination.

  • W. McCune, Solution of the Robbins Problem (1997) — on unification modulo AC in the program EQP, which does the same as our tactic ac, but inside the search.