Zulip Chat Archive
Stream: new members
Topic: Overload a function with a strucure and its extensions
Tianchen Zhao (Jul 09 2021 at 14:57):
If I define a structure A and a map f on it, how can I overload f with B which extends A? Is there any good solutions to make f work for both A and B?
structure A := (pts : ℕ)
structure B extends A
variables (a : A) (b : B) (f : A → ℕ)
#check f a --ℕ
#check f b --type error
Kevin Buzzard (Jul 09 2021 at 14:58):
You can use a coercion to map A to B and define f from B to nat.
Kevin Buzzard (Jul 09 2021 at 15:00):
structure A := (pts : ℕ)
structure B extends A
instance : has_coe A B := ⟨λ a, { pts := a.pts }⟩
variables (a : A) (b : B) (f : B → ℕ)
#check f a -- ℕ
#check f b -- ℕ
Kevin Buzzard (Jul 09 2021 at 15:01):
or
structure A := (pts : ℕ)
structure B extends A
instance : has_coe B A := ⟨B.to_A⟩
variables (a : A) (b : B) (f : A → ℕ)
#check f a -- ℕ
#check f b -- ℕ
Last updated: Dec 20 2023 at 11:08 UTC