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 HaskHaskHask \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 CC 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 SrcSrc and TgtTgt a functor is defined as two assignments, one of which sends objects to objects and the other which sends morphisms to morphisms:

SrcTrgAFAfF(f)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:

AidAAFAidFAFAF(idA)=idFAA \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 AfBA \xrightarrow {f} B in the source category SrcSrc the morphism FAF(f)FBFA \xrightarrow {F(f)} FB in TgtTgt can be preserved or it can be reversed. This leads to two kinds of functors, covariant and contravariant:

covariantAfBFAF(f)FBcontravariantAfBFBF(f)FAcovariant \\ A \xrightarrow {f} B \longmapsto FA \xrightarrow {F(f)} FB \\ contravariant \\ A \xrightarrow {f} B \longmapsto FB \xrightarrow {F(f)} FA

An example of a functor in Haskell

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

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

In order to prove that MaybeMaybe 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!