Skip to content

Commit c669471

Browse files
committed
fix(Tactic/Algebra): properly handle scalars that evaluate to zero (#39444)
When `algebra` encounters `0 • x` it gets normalized to `0 • x` instead of `0`, breaking the invariant that coefficients are not allowed to be zero. This PR fixes this issue and adds a corresponding test.
1 parent 0956725 commit c669471

3 files changed

Lines changed: 18 additions & 3 deletions

File tree

Mathlib/Tactic/Algebra/Basic.lean

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -195,9 +195,14 @@ def cast (cR : Algebra.Cache sR) (u' : Level) (R' : Q(Type u'))
195195
let ⟨r, pf_smul⟩ ← evalSMulCast q($sAlg) q($_smul) r'
196196
let ⟨_r'', vr, pr⟩ ←
197197
Common.eval rcℕ (Ring.ringCompute cR.toCache) cR.toCache q($r)
198-
assumeInstancesCommute
199-
return ⟨_, Common.ExSum.add (Common.ExProd.const (.mk _ vr)) .zero,
200-
q(cast_smul_eq_mul $pr $pf_smul)⟩
198+
match vr with
199+
| .zero .. =>
200+
assumeInstancesCommute
201+
return ⟨_, .zero, q(cast_zero_smul_eq_zero_mul $pr $pf_smul)⟩
202+
| vr =>
203+
assumeInstancesCommute
204+
return ⟨_, Common.ExSum.add (Common.ExProd.const (.mk _ vr)) .zero,
205+
q(cast_smul_eq_mul $pr $pf_smul)⟩
201206

202207
/-- Evaluate the product of two normalized expressions in `R` using `ring`. -/
203208
def neg (cR : Algebra.Cache sR) {a : Q($A)} (_rA : Q(CommRing $A)) (za : BaseType sAlg a) :

Mathlib/Tactic/Algebra/Lemmas.lean

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,12 @@ theorem add_algebraMap_isNat_zero {r s : R} (h : r + s = 0) :
190190
rw [← map_add, h, map_zero]
191191
exact ⟨by simp⟩
192192

193+
/- RingCompute.cast -/
194+
theorem cast_zero_smul_eq_zero_mul {R' : Type*} [HSMul R' A A] {r' : R'} {r : R}
195+
(hr : r = 0) (h_smul : ∀ (a : A), r • a = r' • a) (a : A) :
196+
r' • a = (0 : A) * a := by
197+
simp [← h_smul, hr]
198+
193199
/- RingCompute.cast -/
194200
theorem cast_smul_eq_mul {R' : Type*} [HSMul R' A A] {r' : R'} {r r'' : R}
195201
(hr : r = r'') (h_smul : ∀ (a : A), r • a = r' • a) (a : A) :

MathlibTest/Algebra.lean

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,3 +148,7 @@ example {A R R' : Type*} [CommRing A] [CommRing R] [CommRing R'] [Algebra R A] [
148148
example {A R R' : Type*} [CommRing A] [CommRing R] [CommRing R'] [Algebra R A] [Algebra R' A] (r : R) (r' : R') (x : A) :
149149
(r : R) • x + (1 : ℕ) • x + (r' : R') • x = (r' : R') • x + (1 : ℕ) • x + (r : R) • x:= by
150150
algebra
151+
152+
/- Ensure that terms are eliminated if the coefficient happens to evaluate to zero. -/
153+
example (x : ℚ) : 0 • x = 0 := by
154+
algebra

0 commit comments

Comments
 (0)