Algebraic data types (ADTs) were introduced in Hope, a small functional programming language developed in the 1970s at the University of Edinburgh.
Algebraic refers to the property that an ADT is created by algebraic operations. The algebra here, is sums, products and patterns:
- sum
-
alternation (for three values A, B, C → A or B or C but not any combination or other subset).
- product
-
combination (for three values A, B, C → A and B and C, possible to hold empty for one or more).
Algebraic data types are also known as composite types - a type formed by combining other types.
Algebraic data types (ADTs) can be identified and analyzed using Pattern Matching.
Let us look at the two common types: sum types and product types.
Sum Types | Product Types | |
---|---|---|
Use |
Define variants |
Hold Values |
Logic |
Logical OR operation (only one of the variants is possible) |
Logical AND operation (combination of several values) |
Content |
Each variant can have its own constructor with specified number of arguments |
Contains several values of possibly different types themselves |
Examples |
|
|
|
Tuple (developer created/third party libraries) |
|
|
|
|
|
Example | Description |
---|---|
Enums in Java |
|
Using Optional in Java |
|
Sealed Types in Java |
Example | Description |
---|---|
A Class in Java |
|
Tuples in Java |
|
Records in Java |
Example | Description |
---|---|
Covariance and Contravariance |
|
A walk-through of the visitor pattern |
|____LICENSE |____README.adoc <----- This file |____assets <----- Images linked above |____src | |____none | | |____cgutils | | | |____algebraic | | | | |____sum <----- Examples of Sum types | | | | |____product <----- Examples of Product types | | | | |____other <----- Examples of patterns