An abstraction to implement a way to map functions to a wide range of data structures like lists, trees etc.

The type for which we implement the functor must be a data or newtype, which can have instances.

A functor implements the function

fmap :: (a -> b) -> f a -> f b

fmap applies a function to a value inside a context and produces a value also inside this context.

The infix version of fmap is written <$>.

Functor Laws

In addition to providing a function fmap of the specified type, functors are also required to satisfy two laws:

fmap id = id
fmap (g . h) = fmap g . fmap h

Examples

instance Functor ((->) r) where
  -- General fmap :: (a -> b) -> f a -> f b
  -- fmap :: (a -> b) -> (r -> a) -> (r -> b)
  -- (.) :: (b -> c) -> (a -> b) -> (a -> c)
  fmap = (.)