A functor, in category theory, is a structural-preserving mapping between categories. Given two categories, and , a functor associates each object in with an object in and each morphism in with a morphism in , such that:
-
for every object in ,
-
for all morphisms and in
That is, functors must preserve identity morphisms and composition of morphisms. We can rephrase these conditions using the subsequent commutative diagram:
\begin{xy} \xymatrix{ F(A) \ar[r]_{F(f)} \ar@/^1.5pc/[rr]^{F(g\ \circ f)} & F(B) \ar[r]_{F(g)} & F(C) \\ A \ar[r]^{f} \ar@/_1.5pc/[rr]_{g\ \circ\ f} \ar[u]_{F} & B \ar[r]^{g} \ar[u]_{F} & C \ar[u]_{F} } \end{xy}Example
A Functor in Haskell is a typeclass that represents a type that can be mapped over, meaning that you can apply a function to every element of the type without changing its structure.
Haskell Definition of Functor (Interface)
The following condition must always hold:
An Instance of Functor, the List Functor
Another Instance, the Maybe Functor
All of the above is already implemented in the standard Haskell library, so you can simply open an interactive Haskell interpreter (ghci) and test the following examples.
Some more examples contains basically everything that can be mapped over:
- Either Functor: If the Either contains a right value, it applies the function to the value, else it leaves the left value untouched.
- IO Functor: Used to construct computations which perform I/O and computes a result.
- Future Functor: Applies a function to a value in a future (a sort of placeholder object for a value that is initially unknown).
- Const Functor: Ignores its function argument and always yields the same value.
- Identity Functor: Simply applies the given function to its argument without any additional behavior.
- Function Functor (in the sense of (a -> b) -> (c -> d)): Applies a function to the return type of another function.
- Tree Functor: Applies a function to every node in a tree.
- Pair Functor: Applies the function to the second element of a pair.
- Reader Functor: Applies a function to the result of another function (a “reader” of some shared environment)
- State Functor: Applies a function to the result of a stateful computation.
- Writer Functor: Applies a function to the result while preserving some additional logging or output.
References
- 0.The diagram displayed at the top of this post is a modified version of Brent Yorgey's Typeclassopedia diagram ↩
- 1.Functor in ncatlab ↩