8 Mar 2007 21:00
Deriving Functor
Hello, I would like to propose to add a way to automatically derive instances of Functor. From looking at existing code, it seems that almost all Functor instances I see are derivable using the algorithm presented here, resulting in less boilerplate code. This proposal is compatible with Haskell98 (and therefore also with Haskell'). Let's start with an example. The following declaration: > data Tree a = Leaf | Node (Tree a) a (Tree a) > deriving Functor would generate the following Functor instance: > instance Functor Tree where > fmap f (Leaf ) = Leaf > fmap f (Node l a r) = Node (fmap f l) (f a) (fmap f r) To be able to derive Functor in a general way, more classes are needed to support functors over other parameters: > class Functor2 f where fmap2 :: (a -> b) -> f a x -> f b x > class Functor3 f where fmap3 :: (a -> b) -> f a x y -> f b x y > -- etc. Provided instances would be: > instance Functor ((,) a) -- currently in Control.Monad.Instances > instance Functor2 (,) > instance Functor ((,,) a b) > instance Functor2 ((,,) a) > instance Functor3 (,,)(Continue reading)

RSS Feed