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:

1
2
Prelude> map (+7) [1,2,3]
[8,9,10]

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:

1
2
3
instance Functor Tree where
fmap f (Leaf x) = Leaf (f x)
fmap f (Branch left right) = Branch (fmap f left) (fmap f right)

And here we define a tree and transform it by adding 7 to each leaf.

1
2
fmap (+7) (Branch (Branch (Leaf 1) (Leaf 2)) (Branch (Leaf 3) (Leaf 4)))
Branch (Branch (Leaf 8) (Leaf 9)) (Branch (Leaf 10) (Leaf 11))

Comments

2017-06-28