# Functors 101

A **functor** is a mapping between categories, possibly including itself, which is called an **endofunctor** (in Haskell we deal with endofunctors, the mapping from $Hask \rightarrow Hask$).

The idea of category theory is that we want to take a collection of 'things', but we don't want to look inside these 'things'. We call them objects, they are nothing more than points at best. We do need to have a way to 'compare' these objects, which is what the morphisms are for. So given a category $C$ we think of all the morphisms between the objects of that category as those things which **compare** the objects.

Now that we have these things called **categories** how do we compare them? **Functors**!

Given a pair of categories $Src$ and $Tgt$ a functor is defined as two assignments, one of which sends objects to objects and the other which sends morphisms to morphisms:

$Src \longrightarrow Trg \\ A \longmapsto FA \\ f \longmapsto F(f)$And of course these assignments must respect the structure of the two categories. By the category laws the functor must preserve identity morphisms:

$A \xrightarrow {id_A} A \longmapsto FA \xrightarrow {id_{FA}} FA \\ F(id_A) = id_{FA}$and composition of composible morphisms is also preserved, but here the direction can be reversed. Given a morphism $A \xrightarrow {f} B$ in the source category $Src$ the morphism $FA \xrightarrow {F(f)} FB$ in $Tgt$ can be preserved or it can be reversed. This leads to two kinds of functors, **covariant** and **contravariant**:

**An example of a functor in Haskell**

$Maybe$ is a coproduct type that encapsulates a unit type and some other type $a$ - it's a sum type of $1 + a$. Here's the definition of $Maybe$:

In order to turn $Maybe$ into a functor (more correctly an endofunctor) we need to make it an instance of the $Functor$ typeclass:

In order to prove that $Maybe$ is indeed a functor we need to prove that the application of the functor preserves the structure of the category - that means identity and function composition:

That's just a brief introduction - there is much more to functors!