leanprover / lean4

Lean 4 programming language and theorem prover
https://lean-lang.org
Apache License 2.0
4.66k stars 418 forks source link

`rw [def]` only works with first applicable equation lemma #5026

Open timotree3 opened 2 months ago

timotree3 commented 2 months ago

Prerequisites

Please put an X between the brackets as you perform the following steps:

Description

When using rw to unfold a recursive definition using equation lemmas, it seems to find the first equation lemma whose LHS appears in the goal, and then find the leftmost occurrence of that LHS in the goal. I would've expected it to find the leftmost subexpression in the goal which matches any of the possible equation lemmas. Similarly, I would expect nth_rw n (AKA rw (config := {occs := .pos [n]})) to find the nth subexpression which matches any of the equation lemmas, not just the first equation lemma.

Context

I first noticed then when a new user was confused by it on Zulip. Then I opened a Zulip thread.

Steps to Reproduce

example (x : α) : [x].length = ([] : List α).length + 1 := by
  rw [List.length] -- unsolved goals; rewrites `[].length = 0` instead of `[x].length = [].length + 1`
  -- expected: solves goal because `rw` applies to leftmost applicable subexpression which is `[x].length`

example (x : α) : [x].length = ([] : List α).length + 1 := by
  rw (config := {occs := .pos [1]}) [List.length] -- error: same as above
  -- expected: same as above

example (x : α) : [x].length = ([] : List α).length + 1 := by
  rw (config := {occs := .pos [2]}) [List.length] -- error; `rw` can't find a second occurence for the `[].length = _` equation
  -- expected: new goal is `⊢ [x].length = 0 + 1`

-- Workaround: Use the specific desired equation lemma
example (x : α) : [x].length = ([] : List α).length + 1 := by
  rw [List.length.eq_2] -- success

Versions

4.12.0-nightly-2024-08-13 live.lean-lang.org

Impact

Add :+1: to issues you consider important. If others are impacted by this issue, please ask them to add :+1: to it.

nomeata commented 2 months ago

Thanks for your report, it’s good to have this noted down.

I agree that the behavior you describe is not as intuitive as it could. But fixing it might be non-trivial (didn’t have a close look at the rw implementation yet) and a work-around exists by specyfing the exact lemma, so I’d say this isn’t going to be of high priority.