Zulip Chat Archive
Stream: new members
Topic: Class extension and instance/reference
Luiz Kazuo Takei (Nov 11 2025 at 18:51):
Suppose I have a class that just extends two other classes:
class TC (α : Type) extends Add α, Mul α
Now I define an object Rn n and make it an instance of Add and Mul:
def Rn (n : ℕ) : Type := Fin n → ℝ
instance : Add (Rn n) where
add := fun v w : (Rn n) ↦ (fun i ↦ v i + w i)
instance : Mul (Rn n) where
mul := fun v w : (Rn n) ↦ (fun i ↦ v i * w i)
My understanding is that, from now on, Lean detects that Rn n is an instance of Add, making this work:
example : Add (Rn n) := inferInstance
But, when I check if Lean automatically knows that Rn n is an instance of TC, it doesn't work:
example : TC (Rn n) := inferInstance
I have two questions:
- The more practical one is: how can I make Lean understand that
Rn nis an instance ofTC? - The more subtle question is: how come Lean doesn't automatically recognize that
Rn nis an instance ofTC?
Ruben Van de Velde (Nov 11 2025 at 18:54):
Presumably there's a typo in your last snippet
Luiz Kazuo Takei (Nov 11 2025 at 18:55):
Thanks @Ruben Van de Velde. Typo fixed!
Ruben Van de Velde (Nov 11 2025 at 18:56):
I understand it's possible to add instance [Add X] [Mul X] : TC X := TC.mk or similar
Luiz Kazuo Takei (Nov 11 2025 at 19:08):
Thanks. A related question. Suppose I only declare that Rn n is an instance of Add:
class TC (α : Type) extends Add α, Mul α
def Rn (n : ℕ) : Type := Fin n → ℝ
instance : Add (Rn n) where
add := fun v w : (Rn n) ↦ (fun i ↦ v i + w i)
and now I want to declare that Rn n is an instance of TC. How can I tell Lean to use the instance of Add so that I can just define Mul?
instance : TC (Rn n) := sorry
Kenny Lau (Nov 11 2025 at 19:17):
@Luiz Kazuo Takei it is automatic:
import Mathlib
class TC (α : Type) extends Add α, Mul α
def Rn (n : ℕ) : Type := Fin n → ℝ
instance : Add (Rn n) where
add := fun v w : (Rn n) ↦ (fun i ↦ v i + w i)
instance : TC (Rn n) where
mul := sorry
Luiz Kazuo Takei (Nov 11 2025 at 19:20):
Thanks!
Eric Wieser (Nov 11 2025 at 20:23):
Ruben Van de Velde said:
I understand it's possible to add
instance [Add X] [Mul X] : TC X := TC.mkor similar
This indeed works (and is cleaner as attribute [instance] TC.mk), but is usually a bad idea
Luiz Kazuo Takei (Nov 11 2025 at 20:44):
@Eric Wieser, I am not sure I understand. You're saying it's better to use attribute [instance] TC.mk? Do you mind showing how that would fit in the code? I had never seen this before.
Eric Wieser (Nov 11 2025 at 20:45):
That spelling is better than Ruben's for minor reasons, but both are not a great idea performance-wise as they make a loop
Eric Wieser (Nov 11 2025 at 20:46):
As for how to use it, you just add it as a line by itself after your class
Last updated: Dec 20 2025 at 21:32 UTC