Tech News
← Back to articles

Algebraic Types are not Scary

read original related products more articles

Algebraic Types are not Scary, Actually Posted on 2025-08-30

You may have heard the term algebraic types before, which initially sounds like an advanced concept, that only someone with a PhD in programming languages can understand. Quite the contrary, algebraic types is a very simple and helpful concept about programming in general. Anyone who knows basic algebra could understand what algebraic types are.

In this article I aim to provide an explanation of algebraic types for the working programmer. I intentionally avoid any terminology that a regular programmer may not know about. I hope by the end of the article you know what algebraic types are and can use it in real programming and spot it where it appears.

Types as Sets

What is a type, really? For instance, when we write int , what does it mean? One useful way to think about it is to treat types as sets. In this perspective, every type is treated as a set of possible values that is compatible with the type. For instance, bool is a type that has only true and false values. In OCaml bool is defined as:

type bool = true | false

In the left hand side we define the type bool . The right side provides the possible values, separated with | .

For integers, this is 0 , 1 or any other integer value. It's a bit more difficult to define integers directly as a regular type because in this case there are infinitely many values that integer can take. Writing all these is impossible. But assuming it was possible, we could write:

type int = ... | -3 | -2 | -1 | 0 | 1 | 2 | 3 | ...

In practice, integer types are usually limited to some finite range (but still too large) but this is not related to what we are discussing here. Strings are very similar to integers from this perspective.

... continue reading