"""Associativity and commutativity as a tactic (deep dive: compression). The sum (b + a) + (c + a) has many equal forms: the two laws A1 x + y = y + x (commutativity) A2 x + y + z = x + (y + z) (associativity) let us reorder and regroup the summands freely. A proof that writes down every swap is long and boring, so Lean has the tactic ac_rfl, which closes such goals in one step. Here is the same idea for our kernel. The tactic sorts the summands into a normal form, but it does not ask for trust: every swap and every regrouping becomes kernel rules (Inst, CongrArg, Symm, Trans), and the kernel checks them all. The script gets shorter; the proof the kernel checks does not. """ from functools import lru_cache from kernel import Refl, Symm, Trans, CongrArg, Inst, subst from syntax import show from tactics import TacticError, fresh, trans, symm def brief(text, width=160): """Long terms in messages: the beginning, … and the end.""" if len(text) <= width: return text return text[:width // 2] + " … " + text[-width // 2:] def is_sum(t): return isinstance(t, tuple) and t[0] == "+" def addends(t): """x + (y + z) -> [x, y, z]: the summands of a sum, left to right.""" if is_sum(t): return addends(t[1]) + addends(t[2]) return [t] def chain(parts): """[x, y, z] -> x + y + z, grouped to the left as Lean prints it.""" result = parts[0] for t in parts[1:]: result = ("+", result, t) return result @lru_cache(maxsize=None) def symbols(t): """The number of symbols in a term.""" if isinstance(t, str): return 1 return 1 + sum(symbols(a) for a in t[1:]) @lru_cache(maxsize=None) def order_key(t): """The order of summands in the normal form: letters first, then longer and longer terms; terms of equal length by their printed text. The printed text of a normal form determines it, so the order is total.""" if isinstance(t, str): return (0, 0, t) return (1, symbols(t), show(t)) @lru_cache(maxsize=None) def normal(t): """The AC normal form: in every sum the summands sorted by `order_key` and grouped to the left. Two terms are equal by A1 and A2 exactly when their normal forms are the same.""" if isinstance(t, str): return t if not is_sum(t): return (t[0],) + tuple(normal(a) for a in t[1:]) parts = sorted((normal(s) for s in addends(t)), key=order_key) return chain(parts) # --- the same normal form, now with a proof --------------------------------- def at(t, path): """The subterm at a path: (1, 2) = the second argument of the first.""" for i in path: t = t[i] return t def put(t, path, u): """t with the subterm at the path replaced by u.""" if not path: return u i = path[0] return t[:i] + (put(t[i], path[1:], u),) + t[i + 1:] class Steps: """A proof of start = now, written one rewrite at a time. step(path, proof) uses a proof of u = w, where u is the subterm at the path: CongrArg puts the rewrite into the whole term, Trans joins it to the steps so far.""" def __init__(self, kernel, t): self.kernel, self.start, self.now = kernel, t, t self.pieces = [] # one proof per rewrite @property def count(self): return len(self.pieces) @property def proof(self): """The pieces joined by Trans into a balanced tree (a long chain nested only to the left would be very deep).""" return balanced(self.pieces) def step(self, path, proof, equation=None): """equation: the (u, w) that the proof justifies, if known — saves computing it (the kernel checks the whole proof at the end).""" u, w = equation or self.kernel.conclusion(proof) if at(self.now, path) != u: raise TacticError(f"no {brief(show(u))} at {path} in " f"{brief(show(self.now))}") z = fresh(self.now, w) piece = proof if path: piece = CongrArg(z, put(self.now, path, z), proof) self.now = put(self.now, path, w) self.pieces.append(piece) def fact(self, path, name, args, backward=False): """One rewrite by the fact `name` for the terms args.""" proof = Inst(name, tuple(args)) u, w = instance(self.kernel, name, args) if backward: self.step(path, Symm(proof), (w, u)) else: self.step(path, proof, (u, w)) def balanced(proofs): """Trans of the proofs p1: a = b, p2: b = c, ... as a balanced tree.""" if not proofs: return None if len(proofs) == 1: return proofs[0] half = len(proofs) // 2 return Trans(balanced(proofs[:half]), balanced(proofs[half:])) def normalize(kernel, t, comm="A1", assoc="A2"): """(normal form of t, proof of t = normal form or None, rewrites).""" steps = Steps(kernel, t) _sort(steps, (), comm, assoc) if steps.now != normal(t): # cannot happen: a safety net raise TacticError("ac: not a normal form: " + brief(show(steps.now))) return steps.now, steps.proof, steps.count def _sort(steps, path, comm, assoc): """Normal form of the subterm at the path: first the arguments, then the sum L + R of two sorted chains is merged into one.""" u = at(steps.now, path) if isinstance(u, str): return for i in range(1, len(u)): _sort(steps, path + (i,), comm, assoc) if is_sum(u): _merge(steps, path, comm, assoc) def _merge(steps, path, comm, assoc): """L + R with L and R sorted chains -> one sorted chain.""" L, R = at(steps.now, path)[1:] if is_sum(R): # L + (R1 + r) = (L + R1) + r R1, r = R[1], R[2] steps.fact(path, assoc, (L, R1, r), backward=True) _merge(steps, path + (1,), comm, assoc) _insert(steps, path, comm, assoc) 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) def ac_proof(kernel, s, t, comm="A1", assoc="A2"): """A proof of s = t when the two terms differ only by A1 and A2.""" ns, ps, _ = normalize(kernel, s, comm, assoc) nt, pt, _ = normalize(kernel, t, comm, assoc) if ns != nt: raise TacticError(f"ac_rfl: {brief(show(ns))} and " f"{brief(show(nt))} differ") return trans(ps, symm(pt)) or Refl(s) def ac_rfl(comm="A1", assoc="A2"): """The tactic ac_rfl: the two sides have the same normal form.""" def tactic(kernel, goal): return ac_proof(kernel, goal[0], goal[1], comm, assoc) return tactic def instance(kernel, name, args): """The equation l = r of the fact `name` for the terms args.""" variables, l, r = kernel.facts[name] s = dict(zip(variables, args)) return subst(l, s), subst(r, s) # --- matching modulo A1 and A2 --------------------------------------------- def ac_match(p, t, free, s): """All substitutions s' ⊇ s of the variables in `free` with normal(p[s']) == t, for a term t in normal form (a generator). A variable in a sum may take several summands: x + n(y) matches a + b + n(c) with x = a + b, y = c. The values in s are normal.""" for s2, rest in _match(p, [t], free, s, exact=True): yield s2 def ac_match_part(p, parts, free, s): """Matches of the sum pattern p against a part of the summands `parts`; yields (substitution, the summands left over).""" yield from _match(p, parts, free, s, exact=False) def _match(p, ts, free, s, exact): if is_sum(p): ps = addends(p) if len(ts) == 1 and not is_sum(ts[0]) and exact: return ts = addends(ts[0]) if len(ts) == 1 else ts rigid = [q for q in ps if not (isinstance(q, str) and q in free)] flexible = [q for q in ps if isinstance(q, str) and q in free] yield from _sum(rigid + flexible, ts, free, s, exact) return if len(ts) != 1: if exact: return for i, t in enumerate(ts): for s2 in _one(p, t, free, s): yield s2, ts[:i] + ts[i + 1:] return for s2 in _one(p, ts[0], free, s): yield s2, [] def _one(p, t, free, s): """Matches of p against one term t (not inside a longer sum).""" if isinstance(p, str): if p not in free: if p == t: yield s elif p not in s: yield {**s, p: t} elif s[p] == t: yield s return if is_sum(p): for s2, rest in _match(p, [t], free, s, exact=True): yield s2 return if isinstance(t, str) or t[0] != p[0] or len(t) != len(p): return def arguments(i, s): if i == len(p): yield s return for s2 in _one(p[i], t[i], free, s): yield from arguments(i + 1, s2) yield from arguments(1, s) def _sum(ps, ts, free, s, exact): """Distribute the summands ts among the pattern summands ps.""" if not ps: if ts or not exact: if not exact: yield s, ts return yield s, [] return q, others = ps[0], ps[1:] if isinstance(q, str) and q in free and q in s: rest = _without(ts, addends(s[q])) if rest is not None: yield from _sum(others, rest, free, s, exact) return if isinstance(q, str) and q in free: need = len(others) # each needs one summand seen = set() for size in range(1, len(ts) - need + 1): for chosen in _subsets(len(ts), size): bundle = sorted((ts[i] for i in chosen), key=order_key) bundle = tuple(bundle) if bundle in seen: continue seen.add(bundle) rest = [t for i, t in enumerate(ts) if i not in chosen] s2 = {**s, q: chain(bundle)} yield from _sum(others, rest, free, s2, exact) return seen = set() for i, t in enumerate(ts): if t in seen: continue seen.add(t) for s2 in _one(q, t, free, s): yield from _sum(others, ts[:i] + ts[i + 1:], free, s2, exact) def _without(whole, part): rest = list(whole) for x in part: if x not in rest: return None rest.remove(x) return rest def _subsets(n, k, start=0): """All k-element sets of indices from start, ..., n - 1.""" if k == 0: yield frozenset() return for i in range(start, n - k + 1): for rest in _subsets(n, k - 1, i + 1): yield rest | {i}