Zulip Chat Archive

Stream: new members

Topic: class instance inside a struct?


Yannick Seurin (Oct 31 2025 at 14:15):

Is it possible to have a class instance inside a structure? E.g., something like:

import Mathlib

structure Foo where
  α : Type
  deq : DecidableEq α

variable {foo : Foo}

def bar [DecidableEq foo.α] (a b : foo.α) :  :=
  if a = b then 1 else 0 -- works

def bar' (a b : foo.α) :  :=
  if a = b then 1 else 0
-- failed to synthesize Decidable (a = b)

Why can't the class inference system find foo.deq when defining bar', and what would be the correct way to do this?

Kenny Lau (Oct 31 2025 at 14:16):

import Mathlib

structure Foo where
  α : Type
  deq : DecidableEq α
attribute [instance] Foo.deq

variable {foo : Foo}

def bar (a b : foo.α) :  :=
  if a = b then 1 else 0

you need to explicitly instruct Lean to register the instance using attribute [instance] Foo.deq

Kenny Lau (Oct 31 2025 at 14:16):

just because it's "there" doesn't mean Lean will automatically use it

Kenny Lau (Oct 31 2025 at 14:17):

but I believe there has been discussions about possibly changing this by allowing attributes in a structure

Yannick Seurin (Oct 31 2025 at 14:20):

Great, thanks! ChatGPT gave me 5 different answers (3 of which were wrong), but not this one :sweat_smile:

Robin Arnez (Oct 31 2025 at 17:47):

It's often a good idea to make the field instance implicit as well, i.e.

structure Foo where
  α : Type
  [deq : DecidableEq α]
attribute [instance] Foo.deq

That way, you can omit the instance when constructing values of type Foo:

structure Foo where
  α : Type
  [deq : DecidableEq α]
attribute [instance] Foo.deq

example : Foo where
  α := Nat

Last updated: Dec 20 2025 at 21:32 UTC