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 Functor
is some sort of container and an associated function fmap
that 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]
.
Maybe
can also be made a functor, such that fmap toUpper (Just 'a')
yields Just 'A'
.
The general type of fmap
shows quite neatly what is going on:
fmap :: Functor f => (a -> b) -> f a -> f b
And the specialized versions may make it clearer. Here's the list version:
fmap :: (a -> b) -> [a] -> [b]
And the Maybe version:
fmap :: (a -> b) -> Maybe a -> Maybe b
You can gain information on the standard Functor
instances by querying GHCI with :i Functor
and many modules define more instances of Functor
s (and other type classes.)
Please don't take the word "container" too seriously, though. Functor
s 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.