I am a beginner in PLFA, when I read the Induction section, I accidentally wrote a +-swap
proof that I can't understand:
+-suc': ∀ (m n: ℕ) → m + suc n ≡ suc (m + n)
+-suc' zero n = refl
+-suc' (suc m) n rewrite +-suc' m n = refl
+-swap: ∀ (m n p: ℕ) → m + (n + p) ≡ n + (m + p)
+-swap zero n p = refl
+-swap (suc m) n p rewrite +-suc' n (m + p) | +-swap m n p = refl
I don't know why this proof is right, so I try to prove it by a chain of equations (which is wrong):
+-swap (suc m) n p =
begin
(suc m) + (n + p)
≡⟨⟩ n + (suc (m + p))
≡⟨ +-suc' n (m + p)⟩
suc (n + (m + p))
≡⟨ cong suc (+-swap m n p)⟩
n + ((suc m) + p)
∎
I know I really don't understand how rewrite
works. I learn from the following document that rewrite will expand into with:
https://agda.readthedocs.io/en/v2.6.2/language/with-abstraction.html#with-rewrite
But I don't find how rewrite containing | expands in the document. I guess the | in rewrite is also a kind of syntactic sugar:
+-swap (suc m) n p rewrite +-suc' n (m + p) | +-swap m n p = refl
will expand into:
+-swap (suc m) n p rewrite +-suc' n (m + p) rewrite +-swap m n p = refl
I tried to replace the second rewrite with with, no problem:
+-swap (suc m) n p rewrite +-suc' n (m + p)
with m + (n + p) | +-swap m n p
... | .(n + (m + p)) | refl = refl
But if I replaced the first rewrite with with, it gives an error:
+-swap (suc m) n p with n + (suc (m + p)) | +-suc' n (m + p)
... | .(suc (n + m + p)) | refl
rewrite +-swap m n p = refl
+-swap (suc m) n p with n + (suc (m + p)) | +-suc' n (m + p)
... | .(suc (n + m + p)) | refl
with m + (n + p) | +-swap m n p
... | .(n + (m + p)) | refl = refl
Error message:
n + m != n of type ℕ
when checking that the given dot pattern suc (n + m + p) matches
the inferred value suc (n + (m + p))
How do multiple rewrites expand into with? How can this proof be accomplished with an equation chain?