I’m trying to learn Haskell and I’m through all the basics. But now I’m stuck, trying to get my head around functors.
I’ve read that “A functor transforms one category into another category”. What does this mean?
I know it’s a lot to ask, but could anyone give me a plain english explanation of functors or maybe a simple use case?
A fuzzy explanation would be that a
Functoris some sort of container and an associated functionfmapthat allows you to alter whatever is contained, given a function that transforms the contained.For instance, lists are this kind of container, such that
fmap (+1) [1,2,3,4]yields[2,3,4,5].Maybecan also be made a functor, such thatfmap toUpper (Just 'a')yieldsJust 'A'.The general type of
fmapshows quite neatly what is going on:And the specialized versions may make it clearer. Here’s the list version:
And the Maybe version:
You can gain information on the standard
Functorinstances by querying GHCI with:i Functorand many modules define more instances ofFunctors (and other type classes.)Please don’t take the word “container” too seriously, though.
Functors are a well-defined concept, but you can often reason about it with this fuzzy analogy.Your best bet in understanding what is going on is simply reading the definition of each of the instances, which should give you an intuition on what is going on. From there it’s only a small step to really formalize your understanding of the concept. What needs to be added is a clarification of what our “container” really is, and that each instance much satisfy a pair of simple laws.