Course page › Code of Lecture 3 › ac.py · 347 lines
the Polish versionraw file

Associativity and commutativity as a tactic (deep dive: compression).

Code with colored syntax: click a line number to get a link to it; an underlined name leads to its definition.

1"""Associativity and commutativity as a tactic (deep dive: compression).
2
3The sum (b + a) + (c + a) has many equal forms: the two laws
4
5 A1 x + y = y + x (commutativity)
6 A2 x + y + z = x + (y + z) (associativity)
7
8let us reorder and regroup the summands freely. A proof that writes down
9every swap is long and boring, so Lean has the tactic ac_rfl, which closes
10such goals in one step. Here is the same idea for our kernel. The tactic
11sorts the summands into a normal form, but it does not ask for trust: every
12swap and every regrouping becomes kernel rules (Inst, CongrArg, Symm,
13Trans), and the kernel checks them all. The script gets shorter; the proof
14the kernel checks does not.
15"""
16
17from functools import lru_cache
18
19from kernel import Refl, Symm, Trans, CongrArg, Inst, subst
20from syntax import show
21from tactics import TacticError, fresh, trans, symm
22
23
24def brief(text, width=160):
25 """Long terms in messages: the beginning, … and the end."""
26 if len(text) <= width:
27 return text
28 return text[:width // 2] + " … " + text[-width // 2:]
29
30
31def is_sum(t):
32 return isinstance(t, tuple) and t[0] == "+"
33
34
35def addends(t):
36 """x + (y + z) -> [x, y, z]: the summands of a sum, left to right."""
37 if is_sum(t):
38 return addends(t[1]) + addends(t[2])
39 return [t]
40
41
42def chain(parts):
43 """[x, y, z] -> x + y + z, grouped to the left as Lean prints it."""
44 result = parts[0]
45 for t in parts[1:]:
46 result = ("+", result, t)
47 return result
48
49
50@lru_cache(maxsize=None)
51def symbols(t):
52 """The number of symbols in a term."""
53 if isinstance(t, str):
54 return 1
55 return 1 + sum(symbols(a) for a in t[1:])
56
57
58@lru_cache(maxsize=None)
59def order_key(t):
60 """The order of summands in the normal form: letters first, then
61 longer and longer terms; terms of equal length by their printed text.
62 The printed text of a normal form determines it, so the order is
63 total."""
64 if isinstance(t, str):
65 return (0, 0, t)
66 return (1, symbols(t), show(t))
67
68
69@lru_cache(maxsize=None)
70def normal(t):
71 """The AC normal form: in every sum the summands sorted by `order_key` and
72 grouped to the left. Two terms are equal by A1 and A2 exactly when
73 their normal forms are the same."""
74 if isinstance(t, str):
75 return t
76 if not is_sum(t):
77 return (t[0],) + tuple(normal(a) for a in t[1:])
78 parts = sorted((normal(s) for s in addends(t)), key=order_key)
79 return chain(parts)
80
81
82# --- the same normal form, now with a proof ---------------------------------
83
84def at(t, path):
85 """The subterm at a path: (1, 2) = the second argument of the first."""
86 for i in path:
87 t = t[i]
88 return t
89
90
91def put(t, path, u):
92 """t with the subterm at the path replaced by u."""
93 if not path:
94 return u
95 i = path[0]
96 return t[:i] + (put(t[i], path[1:], u),) + t[i + 1:]
97
98
99class Steps:
100 """A proof of start = now, written one rewrite at a time.
101
102 step(path, proof) uses a proof of u = w, where u is the subterm at
103 the path: CongrArg puts the rewrite into the whole term, Trans joins
104 it to the steps so far."""
105
106 def __init__(self, kernel, t):
107 self.kernel, self.start, self.now = kernel, t, t
108 self.pieces = [] # one proof per rewrite
109
110 @property
111 def count(self):
112 return len(self.pieces)
113
114 @property
115 def proof(self):
116 """The pieces joined by Trans into a balanced tree (a long chain
117 nested only to the left would be very deep)."""
118 return balanced(self.pieces)
119
120 def step(self, path, proof, equation=None):
121 """equation: the (u, w) that the proof justifies, if known — saves
122 computing it (the kernel checks the whole proof at the end)."""
123 u, w = equation or self.kernel.conclusion(proof)
124 if at(self.now, path) != u:
125 raise TacticError(f"no {brief(show(u))} at {path} in "
126 f"{brief(show(self.now))}")
127 z = fresh(self.now, w)
128 piece = proof
129 if path:
130 piece = CongrArg(z, put(self.now, path, z), proof)
131 self.now = put(self.now, path, w)
132 self.pieces.append(piece)
133
134 def fact(self, path, name, args, backward=False):
135 """One rewrite by the fact `name` for the terms args."""
136 proof = Inst(name, tuple(args))
137 u, w = instance(self.kernel, name, args)
138 if backward:
139 self.step(path, Symm(proof), (w, u))
140 else:
141 self.step(path, proof, (u, w))
142
143
144def balanced(proofs):
145 """Trans of the proofs p1: a = b, p2: b = c, ... as a balanced tree."""
146 if not proofs:
147 return None
148 if len(proofs) == 1:
149 return proofs[0]
150 half = len(proofs) // 2
151 return Trans(balanced(proofs[:half]), balanced(proofs[half:]))
152
153
154def normalize(kernel, t, comm="A1", assoc="A2"):
155 """(normal form of t, proof of t = normal form or None, rewrites)."""
156 steps = Steps(kernel, t)
157 _sort(steps, (), comm, assoc)
158 if steps.now != normal(t): # cannot happen: a safety net
159 raise TacticError("ac: not a normal form: "
160 + brief(show(steps.now)))
161 return steps.now, steps.proof, steps.count
162
163
164def _sort(steps, path, comm, assoc):
165 """Normal form of the subterm at the path: first the arguments, then
166 the sum L + R of two sorted chains is merged into one."""
167 u = at(steps.now, path)
168 if isinstance(u, str):
169 return
170 for i in range(1, len(u)):
171 _sort(steps, path + (i,), comm, assoc)
172 if is_sum(u):
173 _merge(steps, path, comm, assoc)
174
175
176def _merge(steps, path, comm, assoc):
177 """L + R with L and R sorted chains -> one sorted chain."""
178 L, R = at(steps.now, path)[1:]
179 if is_sum(R): # L + (R1 + r) = (L + R1) + r
180 R1, r = R[1], R[2]
181 steps.fact(path, assoc, (L, R1, r), backward=True)
182 _merge(steps, path + (1,), comm, assoc)
183 _insert(steps, path, comm, assoc)
184
185
186def _insert(steps, path, comm, assoc):
187 """P + x with P a sorted chain: move x left to its place (insertion
188 sort; one swap of neighbours = A2, then A1, then A2 backwards)."""
189 P, x = at(steps.now, path)[1:]
190 if not is_sum(P):
191 if order_key(x) < order_key(P):
192 steps.fact(path, comm, (P, x)) # P + x = x + P
193 return
194 P1, y = P[1], P[2]
195 if order_key(x) >= order_key(y):
196 return
197 steps.fact(path, assoc, (P1, y, x)) # (P1 + y) + x
198 steps.fact(path + (2,), comm, (y, x)) # = P1 + (y + x)
199 steps.fact(path, assoc, (P1, x, y), backward=True) # = (P1 + x) + y
200 _insert(steps, path + (1,), comm, assoc)
201
202
203def ac_proof(kernel, s, t, comm="A1", assoc="A2"):
204 """A proof of s = t when the two terms differ only by A1 and A2."""
205 ns, ps, _ = normalize(kernel, s, comm, assoc)
206 nt, pt, _ = normalize(kernel, t, comm, assoc)
207 if ns != nt:
208 raise TacticError(f"ac_rfl: {brief(show(ns))} and "
209 f"{brief(show(nt))} differ")
210 return trans(ps, symm(pt)) or Refl(s)
211
212
213def ac_rfl(comm="A1", assoc="A2"):
214 """The tactic ac_rfl: the two sides have the same normal form."""
215 def tactic(kernel, goal):
216 return ac_proof(kernel, goal[0], goal[1], comm, assoc)
217 return tactic
218
219
220def instance(kernel, name, args):
221 """The equation l = r of the fact `name` for the terms args."""
222 variables, l, r = kernel.facts[name]
223 s = dict(zip(variables, args))
224 return subst(l, s), subst(r, s)
225
226
227# --- matching modulo A1 and A2 ---------------------------------------------
228
229def ac_match(p, t, free, s):
230 """All substitutions s' ⊇ s of the variables in `free` with
231 normal(p[s']) == t, for a term t in normal form (a generator).
232
233 A variable in a sum may take several summands: x + n(y) matches
234 a + b + n(c) with x = a + b, y = c. The values in s are normal."""
235 for s2, rest in _match(p, [t], free, s, exact=True):
236 yield s2
237
238
239def ac_match_part(p, parts, free, s):
240 """Matches of the sum pattern p against a part of the summands
241 `parts`; yields (substitution, the summands left over)."""
242 yield from _match(p, parts, free, s, exact=False)
243
244
245def _match(p, ts, free, s, exact):
246 if is_sum(p):
247 ps = addends(p)
248 if len(ts) == 1 and not is_sum(ts[0]) and exact:
249 return
250 ts = addends(ts[0]) if len(ts) == 1 else ts
251 rigid = [q for q in ps if not (isinstance(q, str) and q in free)]
252 flexible = [q for q in ps if isinstance(q, str) and q in free]
253 yield from _sum(rigid + flexible, ts, free, s, exact)
254 return
255 if len(ts) != 1:
256 if exact:
257 return
258 for i, t in enumerate(ts):
259 for s2 in _one(p, t, free, s):
260 yield s2, ts[:i] + ts[i + 1:]
261 return
262 for s2 in _one(p, ts[0], free, s):
263 yield s2, []
264
265
266def _one(p, t, free, s):
267 """Matches of p against one term t (not inside a longer sum)."""
268 if isinstance(p, str):
269 if p not in free:
270 if p == t:
271 yield s
272 elif p not in s:
273 yield {**s, p: t}
274 elif s[p] == t:
275 yield s
276 return
277 if is_sum(p):
278 for s2, rest in _match(p, [t], free, s, exact=True):
279 yield s2
280 return
281 if isinstance(t, str) or t[0] != p[0] or len(t) != len(p):
282 return
283
284 def arguments(i, s):
285 if i == len(p):
286 yield s
287 return
288 for s2 in _one(p[i], t[i], free, s):
289 yield from arguments(i + 1, s2)
290 yield from arguments(1, s)
291
292
293def _sum(ps, ts, free, s, exact):
294 """Distribute the summands ts among the pattern summands ps."""
295 if not ps:
296 if ts or not exact:
297 if not exact:
298 yield s, ts
299 return
300 yield s, []
301 return
302 q, others = ps[0], ps[1:]
303 if isinstance(q, str) and q in free and q in s:
304 rest = _without(ts, addends(s[q]))
305 if rest is not None:
306 yield from _sum(others, rest, free, s, exact)
307 return
308 if isinstance(q, str) and q in free:
309 need = len(others) # each needs one summand
310 seen = set()
311 for size in range(1, len(ts) - need + 1):
312 for chosen in _subsets(len(ts), size):
313 bundle = sorted((ts[i] for i in chosen), key=order_key)
314 bundle = tuple(bundle)
315 if bundle in seen:
316 continue
317 seen.add(bundle)
318 rest = [t for i, t in enumerate(ts) if i not in chosen]
319 s2 = {**s, q: chain(bundle)}
320 yield from _sum(others, rest, free, s2, exact)
321 return
322 seen = set()
323 for i, t in enumerate(ts):
324 if t in seen:
325 continue
326 seen.add(t)
327 for s2 in _one(q, t, free, s):
328 yield from _sum(others, ts[:i] + ts[i + 1:], free, s2, exact)
329
330
331def _without(whole, part):
332 rest = list(whole)
333 for x in part:
334 if x not in rest:
335 return None
336 rest.remove(x)
337 return rest
338
339
340def _subsets(n, k, start=0):
341 """All k-element sets of indices from start, ..., n - 1."""
342 if k == 0:
343 yield frozenset()
344 return
345 for i in range(start, n - k + 1):
346 for rest in _subsets(n, k - 1, i + 1):
347 yield rest | {i}