In the Functor
class type definition:
class Functor f where
fmap :: (a -> b) -> f a -> f b
Why does fmap
not have a default implementation? Something like that:
class Functor f where
fmap :: (a -> b) -> f a -> f b
fmap fn (f a) = (f $ (fn) a)
When I write instances of Functor
, I write the same code for each instance manually. Is there a way for me to specify a default implementation?
You probably want this:
{-# LANGUAGE DeriveFunctor #-}
data T1 a = T1 a
deriving Functor
data T2 a = T2 a
deriving Functor
As to why there's no default implementation for functor: your proposal only works if f
is the identity functor (up to isomorphism). That is, it works on
data F a = F a
but it is not going to work on
data F a = F a a
or
data F a = F (Int -> a) [a] (Maybe a)
which require more complex fmap
s.
While one can not write a default fmap
which works in every case, in many simple cases such as the above ones it seems trivial to spot what fmap
should be.
Fortunately, we now have derive Functor
which covers these simple cases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With