I run into this situation often enough for it to be annoying.
Let's say I have a sum type which can hold an instance of x
or a bunch of other things unrelated to x
-
data Foo x = X x | Y Int | Z String | ...(other constructors not involving x)
To declare a Functor instance I have to do this -
instance Functor Foo where
fmap f (X x) = X (f x)
fmap _ (Y y) = Y y
fmap _ (Z z) = Z z
... And so on
Whereas what I would like to do is this -
instance Functor Foo where
fmap f (X x) = X (f x)
fmap _ a = a
i.e. I only care about the X
constructor, all other constructors are simply "passed through". But of course this wouldn't compile because a
on the left hand side is a different type from the a
on the right hand side of the equation.
Is there a way I can avoid writing this boilerplate for the other constructors?