Zulip Chat Archive

Stream: lean4

Topic: Recursive Functor map definition


James Sully (Jun 02 2023 at 04:50):

Hi, I have the following:

instance : Functor BinTree where
  map f t := match t with
  | BinTree.leaf => BinTree.leaf
  | BinTree.branch l x r => BinTree.branch (map f l) (f x) (map f r)

This gives unknown identifier 'map'. With Functor.map instead, I get failed to synthesize instance Functor BinTree. How do I write a recursive typeclass method?

Henrik Böving (Jun 02 2023 at 05:12):

You implement it is a separate function and provide the instwce to the type class mechanism

Henrik Böving (Jun 02 2023 at 05:12):

But it would indeed be very cool if this worked ^^

James Sully (Jun 02 2023 at 09:00):

ah, thanks very much

James Sully (Jun 02 2023 at 09:00):

yep that worked

James Sully (Jun 02 2023 at 09:01):

I don't hate that to be honest, it feels organised to have a separate named map in the relevant namespace for each type

Alex Keizer (Jun 02 2023 at 13:46):

If for some reason you don't want to add a separate definition, you can also make do with

let rec map := fun f t => ...

James Sully (Jun 02 2023 at 13:51):

ah, I wasn't aware you could have a let immediately inside an instance where

Alex Keizer (Jun 03 2023 at 20:41):

Ah, no you can't. It would be:

instance : Functor BinTree where
  map :=
    let rec map := fun f t => ...
    map

Last updated: Dec 20 2023 at 11:08 UTC