Functors in Haskell
A Functor in Haskell is a type class.
What is a type class?
A type class represents a set of variables that have certain properties.
For example in Haskell the Eq type class represents things that can be equated.
The Show type class serves as an interface for things that can be displayed as strings.
The Functor type class represents an item that can have a function being applied to its elements.
For example a list is a functor because we can apply a function to all elements and generate
a new list as a result:
|
In the example above we produce a new list by adding 7 to all of the elements.
If we want to describe the Functor in terms of Category Theory we can say that a Functor is a
transformation between categories.
What is a Category?
A category is a collection.
In our example the list of numbers [1,2,3] is a Category and the ability to transform this list
to the list [8,9,10] by applying a function is represented by the Functor type class.
So if we define our own type and specify that the type is a Functor we mean that a collection
of this type(a Category) can be transformed to another collection(a Category) by applying a
function.
Here is an example of the definition of the Tree type as an instance of the Functor type class:
And here we define a tree and transform it by adding 7 to each leaf.
|