{-# LANGUAGE FlexibleInstances #-} import Prelude hiding (Functor, fmap) -- A functor is a structure with a map on all elements -- (in a container structure of type constructor tc): class Functor tc where fmap :: (a -> b) -> tc a -> tc b -- type constructor class! -- Functor instances: instance Functor [] where fmap = map -- General increment for all Functor containers: incAll :: Functor tc => tc Int -> tc Int incAll = fmap (+1) -- NOTE: functor instances can be defined for any type constructor -- expecting one type argument, i.e., also for the Either constructor -- applied to some type variable: -- data Either a b = Left a | Right b --instance Functor (Either a) where -- fmap _ (Left x) = Left x -- fmap f (Right x) = Right (f x) -- > incAll (Right 41) -- Right 42 -- > incAll (Left "Hello") -- Left "Hello" -- NOTE: the following instance requires a language extension set by -- {-# LANGUAGE FlexibleInstances #-} instance Functor (Either String) where fmap _ (Left x) = Left (x ++ x) fmap f (Right x) = Right (f x) -- > incAll (Left "Hello") -- Left "HelloHello" -- > incAll (Right 41) :: Either String Int -- Right 42