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 ).
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 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 and a functor is defined as two assignments, one of which sends objects to objects and the other which sends morphisms to morphisms:
And of course these assignments must respect the structure of the two categories. By the category laws the functor must preserve identity morphisms:
and composition of composible morphisms is also preserved, but here the direction can be reversed. Given a morphism in the source category the morphism in 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
is a coproduct type that encapsulates a unit type and some other type - it's a sum type of . Here's the definition of :
In order to turn into a functor (more correctly an endofunctor) we need to make it an instance of the typeclass:
In order to prove that 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!