Algebraic” refers to the property that an Algebraic Data Type is created by “algebraic” operations. The “algebra” here is “sums” and “products”:
- “sum” is alternation (
A | B, meaningAorBbut not both) - “product” is combination (
A B, meaningAandBtogether)
Products
A product is a way to combine multiple values of different types into one. They’re present in pretty much all languages, often called “structs”, “records” or “tuples”. In object-oriented programming, a class made up of public fields acts as a product type.
Here are a few examples from different languages:
// Haskell
data Foo = Foo Int String
// Haskell
type Foo = (Int, String)
// TypeScript
type Foo = { bar : string; baz : int }
// C/C++
struct Foo {
char* bar;
int baz;
}Sums
A sum type is another way of building larger types out of smaller ones. Instead of combining two values into one, a sum type is a value that is either one type or another. It’s the “or” to the product type’s “and”.
Sum types are a bit rarer than products. Many languages with product types have no native version of sum types. In languages that have them, they are called “sum types”, “variants”, “tagged unions” or “enums”.
Here is an example from Haskell:
data Foo = Bar Int | Baz String
Note how we have multiple tags (bar and baz) that each have an associated value of, potentially, a different type (Int and String in this example).
A number of features many languages have built-in can be expressed with sum types as a library, like booleans:
data Bool = False | True
Nullable types:
data Nullable a = Null | Just a
Error-handling:
data Error err a = Error err | Result a
https://blog.softwaremill.com/algebraic-data-types-in-four-languages-858788043d4e