Zulip Chat Archive

Stream: general

Topic: default implementations of type class in hierarchy


Bernd Losert (Apr 26 2022 at 21:50):

Say I have the following:

class Foo (α : Type*) :=
(foo : nat)

class Bar (α : Type*) extends Foo α :=
(bar : nat)

I would like some kind of mechanism (a macro?) that will allow me to define an instance of Bar by just specifying bar and having it use that implementation for foo. In other others, I want to write

instance : Bar nat := { bar := 10 }

and have it automatically set foo := 10 as well. Is this possible?

Jireh Loreaux (Apr 26 2022 at 21:57):

IIRC, I think you can just add (to_Foo := default_def_here) to the declaration of the Bar class (syntax might be different in Lean 4, and it's also possible I've botched this entirely). Is that what you're looking for?

Bernd Losert (Apr 26 2022 at 21:58):

Let me try. I'm using Lean 3.

Jireh Loreaux (Apr 26 2022 at 21:58):

Oh, your capitalization threw me off.

Bernd Losert (Apr 26 2022 at 21:58):

Oh cool. You're right. Nice.

Yaël Dillies (Apr 26 2022 at 21:59):

class Bar (α : Type*) extends Foo α :=
(bar : nat)
(foo := bar)

Bernd Losert (Apr 26 2022 at 22:00):

Yep. For some reason, I was reluctant to try the obvious.

Yaël Dillies (Apr 26 2022 at 22:01):

What distinguishes new fields from new default values is whether you specify the type or not. For example, this throws an error:

class Bar (α : Type*) extends Foo α :=
(bar : nat)
(foo : nat := bar) -- `foo` is already a field of `Foo`

Bernd Losert (Apr 26 2022 at 22:01):

I see. Didn't know that.


Last updated: Dec 20 2023 at 11:08 UTC