Zulip Chat Archive

Stream: general

Topic: repeat rw [add_comm] no longer harmful


Kevin Buzzard (Sep 26 2023 at 10:42):

Ha! I just wrote a short paragraph in NNG4 warning users about the dangers of repeat rw [add_comm] because it can lead to loops (and this was a common question in NNG3 -- "why did lean hang after I put it into an infinite loop?"). I then tested it on an example and it didn't hang! And indeed this is also true in core Lean:

example (a b c : Nat) : a + b + c = a + c + b := by
  rw [Nat.add_comm]
  rw [Nat.add_comm]
  rw [Nat.add_comm]
  rw [Nat.add_comm]
  -- you can do it as long as you like. But
  repeat rw [Nat.add_comm]
  -- doesn't hang Lean
  sorry

Is this a bug? ;-) The tactic is not doing what its docstring says it will do, as far as I can see.

Mario Carneiro (Sep 26 2023 at 10:45):

probably because it does it 100000 times and then stops

Mario Carneiro (Sep 26 2023 at 10:46):

does it actually typecheck if you fill in the sorry?

Mario Carneiro (Sep 26 2023 at 10:48):

actually it seems to stop far short of that, you can see by putting your cursor in the repeat that it runs around 124 times

Mario Carneiro (Sep 26 2023 at 10:52):

It appears to be limited by maxRecDepth, it produces n goals if the rec depth is set to 4*n+16

Damiano Testa (Sep 26 2023 at 10:53):

Also, closing the goal does not seem a problem:

example (a b c : Nat) : a + b + c = a + c + b := by
  rw [Nat.add_comm]
  rw [Nat.add_comm]
  rw [Nat.add_comm]
  rw [Nat.add_comm]
  -- you can do it as long as you like. But
  repeat rw [Nat.add_comm]
  rw [ Nat.add_assoc, Nat.add_comm _ a]

-- appears to work

Mario Carneiro (Sep 26 2023 at 10:53):

and the reason is because the implementation of repeat is non-tail-recursive so it fails with a recursion overflow fairly quickly

Mario Carneiro (Sep 26 2023 at 10:53):

syntax "repeat " tacticSeq : tactic
macro_rules
  | `(tactic| repeat $seq) => `(tactic| first | ($seq); repeat $seq | skip)

Mario Carneiro (Sep 26 2023 at 10:54):

repeat' is an elab and able to handle much larger recursions

Kevin Buzzard (Sep 26 2023 at 11:03):

Oh I see, so it really does fail and then stop!


Last updated: Dec 20 2023 at 11:08 UTC