# beuke.org

## A personal blog about computer science topics.

Functor
A Homomorphism of Categories
Posted on Aug 30 2023 ~ 4 min read A functor, in category theory, is a structural-preserving mapping between categories. Given two categories, $\mathcal{C}$ and $\mathcal{D}$, a functor $F: \mathcal{C} \rightarrow \mathcal{D}$ associates each object in $\mathcal{C}$ with an object in $\mathcal{D}$ and each morphism $f : X \rightarrow Y$ in $\mathcal{C}$ with a morphism $F(f) : F(X) \rightarrow F(Y)$ in $\mathcal{D}$, such that:

• $F(id_{X}) = id_{F(X)}$ for every object $X$ in $\mathcal{C}$,

• $F(g \circ f) = F(g) \circ F(f)$ for all morphisms $f : X \rightarrow Y$ and $g : Y \rightarrow Z$ in $\mathcal{C}$

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(X) \ar[r]_{F(f)} \ar@/^1.5pc/[rr]^{F(g\ \circ f)} & F(Y) \ar[r]_{F(g)} & F(Z) \\ X \ar[r]^{f} \ar@/_1.5pc/[rr]_{g\ \circ\ f} \ar[u]_{F} & Y \ar[r]^{g} \ar[u]_{F} & Z \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.

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.

1. 0.The diagram displayed at the top of this post is a modified version of Brent Yorgey's Typeclassopedia diagram
2. 1.