Introduction to Functors

Explanation of Functor. A new Functor, f b, can be made from another Functor f a by transforming all of its value(s), whilst leaving the structure of f unchanged.

Syntax
1
2
class Functor f where
fmap :: (a -> b) -> f a -> f b

Its minimal complete definition is fmap.

Methods
1
2
3
4
5
6
7
8
9
10
11
12
13
-- create a `f b` by calling function on each value in `f a`
fmap :: (a -> b) -> f a -> f b
-- infix form of `fmap`
(<$>) :: (a -> b) -> f a -> f b

-- create a `f a` by replacing all values in `f b` by `a`
(<$) :: a -> f b -> f a

-- almost the same, by reserving argument positions
($>) :: f a -> b -> f b

-- ignoring the values in `f a`.
void :: Functor f => f a -> f ()

Functor Laws

Types of Functor class must satisfy 22 constraints:

  1. Identity. When performing the mapping operation, if the values in the functor are mapped to themselves, the result will be an unmodified functor.
1
fmap id = id
  1. Composition.
Composition
1
fmap (f . g) = fmap f . fmap g