We’ve covered a lot of topics in Scalaz but before moving forward, I’d like to cover functors, monoids, monads, etc. These form the basis of functional programming and are predicated in category theory. This post is intended to be an introduction to category theory.

## What is Category Theory?

Category theory is a mathematical theory involving the study of categories. A category consists of a group of objects and transformations between them. Think of a category as a simple collection.^{[1]}

Formally, a category

- a collection of
**objects** - a collection of
**arrows**(called**morphisms**) - operations assigning each arrow
an object , its **domain**, and an object, its **codomain**. We write this as - a composition operator assigning each pair of arrows
and , with a composite arrow , satisfying the *associative law*:

for any arrows, , and (with , , , and not necessarily distinct), - for each object
, an **identity arrow**satisfying the *identity law*:

for any arrow, and

The formal definition above is taken verbatim from Basic Category Theory for Computer Scientists.

Let’s relate the diagram above^{[2]} to the formal definition that we have. This simple category **objects** **identity arrows** **identity law**. For example,

## A More Concrete Example

Let’s consider a category

is a collection of sets i.e. each object is a set. - an arrow
is a morphism from set to set - for each function
, we have , and - the composition of a function
with is a function from to mapping each element to - for each set
, the identity function is a function with domain and codomain as .

### Code

Let’s begin by creating our first object of category

1 | @ val A = Set("apples", "oranges") |

Next, let’s define a function

1 | @ def f(a: Set[String]): Set[String] = a map { _.reverse } |

Next, let’s morph

1 | @ val B = f(A) |

The domain of

Next, let’s define a function

1 | @ def g(b: Set[String]): Set[Int] = b map { _.length } |

Now let’s compose

1 | @ val C = g(f(A)) |

And finally, let’s create an identity function

1 | @ def idA(a: Set[String]): Set[String] = a map identity |

Let’s see this in action

1 | @ idA(A) |

This is how we translate a category to code. In the coming posts we’ll cover more category theory.