# What's the relation between OOP and category theory?

What's the relation between OOP and category theory? Is there some related work on this topic one can read?

Update (2020)

Have a look at this year's CPPCon talk - Monoids, Monads, and Applicative Functors: Repeated Software Patterns

Also look for mentions of the Fin category in Category Theory in Context

Objects can implement category theoretic data types and access patterns.

For a better understanding I would recommend Stepanov's book , Mike Stay's article, and his more recent blog on Category Theory in Javascript.

Use composition not inheritance.

Use sum types like enums to shrink the state space of your variables.

Use product types (tuples) like std::pair in C++.

If you have a function like A someFunc(A a, B b, C c); the state space from the type signature is |A|^(|A||B||C|). Beware of functions that take many arguments as the state space of your function is astronomical.

• For those who would bother reading the links — they're simply about implementing category theory concepts in OOP languages. I didn't find there the relation, i.e. things like OOP from the view point of category theory, critique or justification of OOP techniques from the view point of category theory, and etc. – Hi-Angel Jan 17 '16 at 11:30

There are absolutely some relationships between the semantics and practice of OOP and category theory. This is somewhat unsurprising since both fields attempt to give a principled generic account of structure and behavior in a synthetic manner.

The most apparent work I am aware of is the categorical semantics of UML, which is admittedly different from OOP in the large, but I think captures much of the crux of the debate on the semantics of objects themselves. One example is Zinovy Diskin's Mathematics of UML.

Bart Jacobs tackled this problem at one point. In his view, classes can be considered as coalgebras. Roughly, we have a polynomial endofunctor $$F : \mathbf{Sets} \to \mathbf{Sets}$$ which gives the class's type signature. A pair of a carrier set $$X$$ and an arrow $$X \to FX$$ is then used to "implement" the class. For example, consider a class representing counters:

class Counter
int GetCurrentVal()
void Increment()


For this class interface, we have $$F(X) \doteq \mathbb Z \times X$$. Each method is represented by a different product component: GetCurrentVal is represented with the left component $$\mathbb Z$$ and Increment is represented with the right component $$X$$. If $$f : X \to \mathbb Z \times X$$ represents an implementation of this class and $$x \in X$$ represents an instance of the class, then the first component $$\pi_1 f(x)$$ is the Counter $$x$$'s current value and $$\pi_2 f(x)$$ is the state of the counter after calling Increment.

The class implementations $$(X \in \mathbf{Sets}_0, f : X \to FX)$$ form a category, where an arrow from $$(X,f)$$ to $$(Y,g)$$ is an arrow $$h : X \to Y$$ in Sets that "preserves observable behavior".