Scenarios: building tactics#

The tactics of the previous parts are written in Python. In the Boole Lab and in the Tactic Lab tactics are composed differently: from ready steps (rw, nth_rw, exact, …) and combinators as in Lean 4 (first | … | …, try, repeat, <;>, …). The scenarios below go the same way as the chapter — from a script, through a tactic, to what the kernel sees — only on smaller examples from Boolean algebra (Huntington’s axioms H1–H8 from lecture 3). We run every scenario here with the Boole Lab engine (Session), so the results are real; the same can be typed in the applet’s terminal:

  • Boole Lab — a terminal with the kernel and the library of theorems, a tactic workshop (the “workshop” button);

  • Tactic Lab — a tactic as a flowchart, a run on a goal and layers: flow, insides of tactics, kernel rules.

import textwrap
from lab import Session

lab = Session("en")          # one session for the whole chapter: theorems thm1, thm2, ...

def session(*commands):
    """Runs Boole Lab commands, prints the replies and returns them as a list of strings."""
    replies = []
    for command in commands:
        print("> " + command)
        replies.append(lab.run(command).text())
        for row in replies[-1].splitlines():
            print(textwrap.fill(row, 100, subsequent_indent="      "))
    return replies

Scenario 1: the script and the proof object#

A proof in the Boole Lab starts with bl prove and ends with qed: then the kernel receives the whole proof and says how many nodes it has. The example tactic units removes “\(+\,0\)” and “\(\cdot\,1\)” — in the script it is one word, in the proof a few steps:

out = session("bl prove x + 0 + x * 1 = x", "units; rw [add_idem]", "qed")
> bl prove x + 0 + x * 1 = x
Proof of thm1 : x + 0 + x * 1 = x
  ⊢ x + 0 + x * 1 = x
> units; rw [add_idem]
  ⚙ 3 steps: rw [H5] · rw [H6] · rw [add_idem]  (tried: 8)
  ✓ no goals — type qed and the kernel checks the whole proof
> qed
✓ the kernel accepted thm1 : x + 0 + x * 1 = x
  proof tree: 7 nodes · assumptions (like #print axioms): H3, H5, H6, H7, H8
  from now on you can use it: rw [thm1] · bl lean thm1

The line ⚙ 3 steps says what the tactic really did: two rewrites with the axioms H5 and H6 and one with the theorem add_idem. The script has two words, the proof for the kernel — seven nodes. It is the same relation as in the Robbins proof, only on a small scale.

Scenario 2: a tactic made of tactics and its measure#

The command bl tactic defines your own tactic. The Boole Lab immediately draws its structure and analyses it: will repeat stop, is some alternative of first unreachable, does try hide a failure.

out = session("bl tactic tidy := repeat (first | rw [H5] | rw [H6])")
> bl tactic tidy := repeat (first | rw [H5] | rw [H6])
✓ tactic tidy := repeat (first | rw [H5] | rw [H6])
  from now on you can use it: tidy · dry run: bl trace tidy
  structure:
    repeat — again and again, while it succeeds
      first — the first alternative that succeeds
        rw [H5]
        rw [H6]
  analysis:
    ✓ repeat stops: every turn makes the goals smaller (the sum of their sizes), and a natural
      number cannot go down forever — H5: x + 0 → x (−2) · H6: x * 1 → x (−2)
  in Lean 4 (bl lean adds it to the file):
    set_option hygiene false in
    macro "tidy" : tactic => `(tactic| (repeat (first | rw [H5] | rw [H6])))

The analysis found a measure of progress: every turn of the loop decreases the sum of the sizes of the goals (H5 and H6 shorten the term by two symbols), and a natural number cannot go down forever. Let us check the tactic on a goal — bl trace runs it as a dry run and shows every turn:

out = session("bl prove (x + 0) * 1 + 0 = x", "bl trace tidy", "tidy", "qed")
> bl prove (x + 0) * 1 + 0 = x
Proof of thm2 : (x + 0) * 1 + 0 = x
  ⊢ (x + 0) * 1 + 0 = x
> bl trace tidy
Trace of tidy   a dry run: the proof state does not change
  ✓ tidy
    ✓ repeat — 3 turns
      ✓ [1] first
        ✓ rw [H5]  ⟶ (x + 0) * 1 = x
      ✓ [2] first
        ✓ rw [H5]  ⟶ x * 1 = x
      ✓ [3] first
        ✗ rw [H5]   no pattern ?x + 0
        ✓ rw [H6]  ⟶ ✓ goal closed
      ✗ [4] first
        ✗ rw [H5]   there is no goal to act on
        ✗ rw [H6]   there is no goal to act on
  result:
    ✓ no goals
  ⚙ 3 steps: rw [H5] ×2 · rw [H6]  (tried: 4)
  apply it: tidy
> tidy
  ⚙ 3 steps: rw [H5] ×2 · rw [H6]  (tried: 4)
  ✓ no goals — type qed and the kernel checks the whole proof
> qed
✓ the kernel accepted thm2 : (x + 0) * 1 + 0 = x
  proof tree: 6 nodes · assumptions (like #print axioms): H5, H6
  from now on you can use it: rw [thm2] · bl lean thm2

In the Tactic Lab the same tactic is a flowchart: a repeat frame with a loop, inside it a first ladder with two rw cards. A run highlights the edges the goal went through.

Scenario 3: a tactic that loops#

Commutativity \(x + y = y + x\) does not shorten the term. A tactic “swap as long as you can” therefore has no measure of progress:

out = session("bl tactic loop := repeat rw [H1]", "bl prove x + y + z = z + (y + x)", "loop")
> bl tactic loop := repeat rw [H1]
✓ tactic loop := repeat rw [H1]
  from now on you can use it: loop · dry run: bl trace loop
  structure:
    repeat — again and again, while it succeeds
      rw [H1]
  analysis:
    ⚠ repeat may loop: H1: x + y → y + x (+0) — this rule keeps the size of the goal, so turns can
      come back to the same goals
  in Lean 4 (bl lean adds it to the file):
    set_option hygiene false in
    macro "loop" : tactic => `(tactic| (repeat rw [H1]))
> bl prove x + y + z = z + (y + x)
Proof of thm3 : x + y + z = z + (y + x)
  ⊢ x + y + z = z + (y + x)
> loop
✗ repeat loops: after turn 2 the goals are the same as before the first turn (x + y + z = z + (y +
      x)) — it would go round forever (in Lean: until the time runs out). Every turn must make the
      goals smaller (bl tactic repeat)
  where it failed: bl trace loop

The Boole Lab warned already at the definition (the rule “keeps the size of the goal”), and when run it detected that after two turns the goal came back to its original form: \(x + y + z \to z + (x + y) \to x + y + z\). In Lean such a tactic would go round until the time limit.

This is the difference between repeat rw [H1] and our tactic ac from part 2: ac also uses commutativity, but only when a swap of neighbours repairs the order. Its measure of progress is the number of inversions — pairs of summands in the wrong order. Every swap decreases it by exactly one:

from robbins import theory
from syntax import term, show
from ac import Steps, addends, order_key
import ac

def inversions(t):
    s = addends(t)
    return sum(order_key(s[i]) > order_key(s[j]) for i in range(len(s)) for j in range(i + 1, len(s)))

K = theory()
steps = Steps(K, term("e + d + c + b + a"))
ac._sort(steps, (), "A1", "A2")
states = [steps.start] + [K.conclusion(k)[1] for k in steps.pieces]
print(" → ".join(str(inversions(t)) for t in states))
print("rewrites:", steps.count, "| inversions at the start:", inversions(steps.start))
10 → 9 → 9 → 8 → 8 → 7 → 7 → 6 → 6 → 6 → 5 → 5 → 4 → 4 → 3 → 3 → 3 → 2 → 2 → 2 → 1 → 1 → 0
rewrites: 22 | inversions at the start: 10

Ten inversions, 22 rewrites: a swap of the first two summands is one step A1, every further one — three steps (A2, A1, A2 backwards). The number of inversions drops by one at every step with A1 and does not change at the steps with A2. The tactic stops for sure, because there are finitely many inversions — and that is the whole difference between loop and ac.

Scenario 4: what the kernel sees#

The command bl lean shows a proof in Lean notation, and your own tactics — as Lean macros. For the theorem of the second scenario:

out = session("bl lean thm2")
> bl lean thm2
-- class HuntingtonAlgebra: lean/Lecture03.lean; open it (open HuntingtonAlgebra)
-- variable {α : Type} [HuntingtonAlgebra α]
set_option hygiene false in
macro "tidy" : tactic => `(tactic| (repeat (first | rw [H5] | rw [H6])))

theorem thm2 (x : α) : (x + 0) * 1 + 0 = x := by
  tidy
  a whole file ready to compile: bl lean thm2 full

The macro is exactly our tactic: Lean expands it when checking into the same rewrites. Neither the Boole Lab nor Lean trust the tactic — they trust the kernel, which checks the result. In the Tactic Lab the same run can be watched on three layers: the flow through the combinators, the insides of named tactics and single kernel rules.

Exercises#

  1. The cost of the tactic ac. For random sums of \(k\) different summands count the nodes of the proof ac_proof and the number of inversions. Check that there are about nine times more nodes than inversions, and explain where the constant comes from.

  2. Two steps on one side. Extend auto so that it allows two rewrites on one side of the goal. Which of the lemmas mann_50 … mann_54 then go through without hints? How long does the search take?

  3. Your own ac in the Boole Lab. The Boole Lab has no tactic ac. Try to compose a tactic from rw steps and combinators that orders a sum of two summands, and explain why for longer sums an order (like order_key) is needed, which the combinators do not know.

  4. The de Bruijn factor. F. Wiedijk measures how many times longer a formal proof is than the mathematical text by comparing file sizes after compression (gzip). Compare in this way lemmas 44–54 in obce/mathlib4/Robbins.lean with our module robbins_proof and with the EQP proof. What does such a number measure, and what does it not?

  5. From Huntington to H1–H8. From Huntington’s equation, A1 and A2 derive in our kernel the axioms H1–H8 of lecture 3: define \(x \cdot y = n(n(x) + n(y))\), \(1 = a + n(a)\), \(0 = n(1)\) and prove the axioms one by one. Which tactics of this chapter will you use most?

  6. Compression in numbers. For the proof of part 3 count how many times each lemma occurs in the tree without lemmas (a function similar to expanded). Which lemma “weighs” the most, and which repeats most often?

References and places worth a visit#

  • W. McCune, Solution of the Robbins Problem, Journal of Automated Reasoning 19(3), 263–276 (1997), DOI.

  • F. Wiedijk, The De Bruijn Factor (TPHOLs 2000).

  • F. Baader, T. Nipkow, Term Rewriting and All That, Cambridge University Press (1998) — rewriting modulo associativity and commutativity, termination measures.

  • S. Wolfram, Who Can Understand the Proof? A Window on Formalized Mathematics (2025) — on proofs that nobody compressed into understandable lemmas.