Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Functor not expose a default implementation of fmap?

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?

like image 899
Andrey Bushman Avatar asked Dec 06 '22 23:12

Andrey Bushman


1 Answers

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 fmaps.

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.

like image 52
chi Avatar answered Dec 09 '22 13:12

chi