Книга: Functional Programming in JavaScript
Назад: Category theory
Дальше: Type safety

Category theory in a nutshell

Category theory really isn't too difficult a concept. Its place in math is large enough to fill up an entire graduate-level college course, but its place in computer programming can be summed up quite easily.

Einstein once said, "If you can't explain it to a 6-year-old, you don't know it yourself". Thus, in the spirit of explaining it to a 6-year-old, category theory is just connecting the dots. Although it may be grossly over-simplifying category theory, it does do a good job of explaining what we need to know in a straightforward manner.

First you'll need to know some terminology. Categories are just sets with the same type. In JavaScript, they're arrays or objects that contain variables that are explicitly declared as numbers, strings, Booleans, dates, nodes, and so on. Morphisms are pure functions that, when given a specific set of inputs, always return the same output. Homomorphic operations are restricted to a single category, while polymorphic operations can operate on multiple categories. For example, the homomorphic function multiplication only works on numbers, but the polymorphic function addition can work on strings too.

Category theory in a nutshell

The following diagram shows three categories—A, B, and C—and two morphisms—ƒ and ɡ.

Category theory tells us that, when we have two morphisms where the category of the first one is the expected input of the other, then they can be composed to the following:

Category theory in a nutshell

The ƒ o g symbol is the composition of morphisms ƒ and g. Now we can just connect the dots.

Category theory in a nutshell

And that's all it really is, just connecting dots.

Назад: Category theory
Дальше: Type safety

bsn
thank
Vesa Karvonen
I hope you don't mind, but I’d like to point you and your readers to my high-performance optics library for JavaScript that is in production use in multiple projects, has comprehensive support for partial optics and interactive documentation: https://calmm-js.github.io/partial.lenses/ (this takes a moment to load — be patient!)