Conceptcore
Algebraic data type
Also called algebraic data type, algebraic datatype, algebraic type, sum of products, data declaration.
An algebraic data type is built from other types with two operations. A product holds one value of each part, and a sum holds one value of one of several cases.
- Applies to
- core-languages
Idea
Many values are built from other values in two ways. Some values have several parts at the same time. A point has an x coordinate and a y coordinate. Other values have one of several forms. A payment is cash, or a card, or a voucher. An algebraic data type is a type built with these two operations, and and or. Wikipedia names them: "An algebraic data type is defined by two key constructions: a sum and a product."1
- A product holds one value of each of its parts. A record, a struct and a tuple are products.
- A sum holds one value of one of a fixed list of cases. Each case has a name, the constructor, and each case can carry its own data. Sum types describes sums in detail.
Most useful types mix the two. A payment is a sum of three cases, and each case is a product of its fields. Haskell defines its algebraic types in this form, as a sum of products.2
from dataclasses import dataclass
@dataclass
class Cash:
amount: int
@dataclass
class Card:
last4: str
amount: int
@dataclass
class Voucher:
code: str
# A sum of three cases. Each case is a product of its fields.
type Payment = Cash | Card | Voucher
def describe(p: Payment) -> str:
match p:
case Cash(amount):
return f"cash {amount}"
case Card(last4, amount):
return f"card ending {last4}, {amount}"
case Voucher(code):
return f"voucher {code}"
for p in [Cash(20), Card("4242", 35), Voucher("SPRING")]:
print(describe(p))
cash 20
card ending 4242, 35
voucher SPRING
A program reads a value of an algebraic data type with pattern matching. The match finds the case, and it gives names to the data of that case.1 See Pattern matching.
How it works
Why the word algebraic. The names come from counting. Count the values of each type. A product of A and B has one value for each combination of a value of A and a value of B, so it has |A| × |B| values. A sum of A and B has the values of A and the values of B, so it has |A| + |B| values.3 The examples on this page check the numbers with a flag of 2 values and a traffic light of 3 values. The pair (flag, light) has 2 × 3 = 6 values. The choice of a flag or a light has 2 + 3 = 5 values.
The empty product and the empty sum. A product with no parts has exactly one value. This is the unit type, "the type of 0-tuples, i.e. the product of no types".4 A sum with no cases has no values. This is the empty type, which "allows no values".4 So the unit type acts as the number 1, and the empty type acts as the number 0. A boolean is the sum of two units, 1 + 1 = 2.3
Constructors. Each case of a sum has a constructor. A constructor takes the fields of its case and gives a value of the whole type. In Haskell, a data declaration "introduces a new type constructor T with zero or more constituent data constructors".5 A constructor with no fields is a constant, such as Nothing or Red. A sum whose constructors all have no fields is an enumeration.1
Type parameters. An algebraic data type can take type parameters. Haskell's Maybe a is Nothing | Just a, and it works for any type a.2 See Generics.
Recursion. A case can contain a value of the type that it belongs to. A list is empty, or it is a head and a tail list. A tree is a leaf, or a branch with two subtrees. The History of Haskell gives this tree: data Tree a = Leaf a | Branch (Tree a) (Tree a).2 In type theory, the list type is written λα.μβ.1+α×β. The empty list is the 1, and a cell is the product of an element and a list.1 See Recursive type.
Matching. A value of a sum records its case. A match, a case or a switch reads the case and binds the fields. The fields of a case exist only inside the branch of that case, so the program cannot read a field of the wrong case. The list of cases is closed, so the compiler can check that a match handles every case.1 Sum types shows this check in each language.
Products and sums in memory. A product stores all of its fields, so its size is at least the sum of the sizes of its fields. A C structure can also have "unnamed padding" between members.6 A sum stores one case and a tag that tells which case it is. A C union has no tag, and its size "is sufficient to contain the largest of its members".6 So a tagged sum needs the tag plus the largest case.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Idiom | |
| C++ | Standard library | |
| Java | Native | |
| C | Idiom | |
| C# | Idiom | |
| JavaScript | Idiom | |
| TypeScript | Native | |
| Go | Idiom | |
| Rust | Native | |
| Kotlin | Native | A data class is a product, and a sealed class or sealed interface whose direct subclasses are data classes is a sum of products; no example file because kotlinc is not installed on the machine that recorded the examples. |
| SQL | Idiom | A row of a table is a product of its columns; a sum is a kind column with one nullable column for each field of each case, or one table for each case. |
| Bash | Does not apply | Bash has no types, only strings and arrays of strings. Alternative: Separate variables for the parts of a product, and a string that holds the kind with a case statement for a sum. |
| PowerShell | Absent | PowerShell has classes, hashtables and enums, but no type whose value is one of a closed set of cases with their own data; no example file because pwsh is not installed on the machine that recorded the examples. Alternative: A class or a hashtable for a product, and an object with a kind property and a switch statement for a sum. |
| HTML | Does not apply | Markup has no types. |
| CSS | Does not apply | Style rules have no types. |
| Regular expressions | Does not apply | A pattern has no types. |
The example files show the counting program in each language: a product of a flag and a light, and a sum of a flag or a light. The table gives the form of products and sums in each language.
| Language | Verdict | Product | Sum |
|---|---|---|---|
| Python | idiom | a dataclass7 or a tuple |
a union A | B of classes, checked by a type checker only8 |
| JavaScript | idiom | an object | an object with a kind field |
| TypeScript | native | an object type or a tuple type | a discriminated union9 |
| Java | native | a record |
a sealed interface with record cases10 |
| C | idiom | a struct6 |
a struct with an enum tag and a union6 |
| C++ | stdlib | a struct, std::pair or std::tuple11 |
std::variant12 |
| C# | idiom | a record13 |
an abstract record with sealed records |
| Go | idiom | a struct |
an interface with a closed set of types, read with a type switch14 |
| Rust | native | a struct or a tuple |
an enum15 |
| Kotlin | native | a data class |
a sealed class or interface16 |
| PowerShell | absent | a class or a hashtable | none |
| Bash | n/a | no types | no types |
| SQL | idiom | a row of a table | a kind column, or one table for each case |
| Regex | n/a | a pattern has no types | a pattern has no types |
| HTML/CSS | n/a | markup has no types | markup has no types |
ML, Haskell, OCaml and F#. In these languages, one declaration defines a sum of products. Haskell 2010 calls it an "algebraic datatype declaration".5 OCaml type definitions bind type constructors to "variant types, record types, type abbreviations, or abstract data types".17 F# has discriminated unions, which "provide support for values that can be one of a number of named cases, possibly each with different values and types".18 F# records "represent simple aggregates of named values".19
Rust and Swift. Both languages use the word enum for a sum, and a struct for a product. The Rust book says that "enums give you a way of saying a value is one of a possible set of values".15 In Swift, enumeration cases "can specify associated values of any type to be stored along with each different case value, much as unions or variants do in other languages".20
Scala. In Scala 3, "The enum concept is general enough to also support algebraic data types (ADTs)".21 Case classes are the products.
Java and Kotlin. Java builds both operations from classes. JEP 409 says: "Record classes allow us to express product types, and sealed classes allow us to express sum types."10 In Kotlin, "All direct subclasses of a sealed class are known at compile time."16 So a sealed class with data classes as its subclasses is a sum of products.
C#. The record modifier tells the compiler to "generate value equality", a formatted ToString and "nondestructive mutation through with expressions".13 A record is a product. The C# of the examples has no closed sum, so an abstract record with sealed records stands for one. Other code can add a case to it, so the compiler cannot check that a switch over it is complete. Sum types describes the union and closed types of C# 15.
Go. Go has structs, but no sums. The Go FAQ says that variant types "overlap in confusing ways with interfaces". An interface value with a type switch takes their place.14
C and C++. A C structure "describes a sequentially allocated nonempty set of member objects", and a C union "describes an overlapping nonempty set of member objects".6 A union does not record which member it holds, so a C program keeps a separate tag. In C++, std::tuple gives "heterogeneous, fixed-size collections of values".11 std::variant holds a value of one of its alternative types, and it knows which one.12
from dataclasses import dataclass
from enum import Enum
from itertools import product
class Light(Enum):
RED = "red"
AMBER = "amber"
GREEN = "green"
# Product: a flag AND a light.
@dataclass(frozen=True)
class Pair:
flag: bool
light: Light
# Sum: a flag OR a light. Each case is a class.
@dataclass(frozen=True)
class Flag:
flag: bool
@dataclass(frozen=True)
class Lamp:
light: Light
type Choice = Flag | Lamp
def yn(b: bool) -> str:
return "yes" if b else "no"
def show(c: Choice) -> str:
match c:
case Flag(flag):
return f"flag:{yn(flag)}"
case Lamp(light):
return f"light:{light.value}"
flags = [False, True]
pairs = [Pair(f, light) for f, light in product(flags, Light)]
choices: list[Choice] = [Flag(f) for f in flags] + [Lamp(light) for light in Light]
print("pairs:", len(pairs))
print(" ".join(f"{yn(p.flag)}/{p.light.value}" for p in pairs))
print("choices:", len(choices))
print(" ".join(show(c) for c in choices))
pairs: 6
no/red no/amber no/green yes/red yes/amber yes/green
choices: 5
flag:no flag:yes light:red light:amber light:green
- Verdict: idiom. A
dataclassis a product. A union of classes,Flag | Lamp, is a sum, andmatchselects the case with class patterns. - The union exists only for a type checker. At run time, nothing stops a list of choices from holding some other object, and
showthen returnsNone. itertools.productbuilds the 2 × 3 combinations of the product.
#include <cstddef>
#include <iostream>
#include <type_traits>
#include <utility>
#include <variant>
#include <vector>
enum class Light { Red, Amber, Green };
const char* name(Light l) {
switch (l) {
case Light::Red: return "red";
case Light::Amber: return "amber";
case Light::Green: return "green";
}
return "?";
}
const char* yn(bool b) { return b ? "yes" : "no"; }
using Pair = std::pair<bool, Light>; // product: a flag AND a light
using Choice = std::variant<bool, Light>; // sum: a flag OR a light
int main() {
const bool flags[] = {false, true};
const Light lights[] = {Light::Red, Light::Amber, Light::Green};
std::vector<Pair> pairs;
std::vector<Choice> choices;
for (bool f : flags) {
for (Light l : lights) pairs.emplace_back(f, l);
choices.emplace_back(f);
}
for (Light l : lights) choices.emplace_back(l);
std::cout << "pairs: " << pairs.size() << "\n";
for (std::size_t i = 0; i < pairs.size(); ++i) {
std::cout << (i ? " " : "") << yn(pairs[i].first) << "/" << name(pairs[i].second);
}
std::cout << "\nchoices: " << choices.size() << "\n";
for (std::size_t i = 0; i < choices.size(); ++i) {
std::cout << (i ? " " : "");
std::visit([](auto v) {
if constexpr (std::is_same_v<decltype(v), bool>) {
std::cout << "flag:" << yn(v);
} else {
std::cout << "light:" << name(v);
}
}, choices[i]);
}
std::cout << "\n";
}
pairs: 6
no/red no/amber no/green yes/red yes/amber yes/green
choices: 5
flag:no flag:yes light:red light:amber light:green
- Verdict: stdlib.
std::pairandstd::tupleare products, andstd::variantis a sum. std::visitcalls the lambda with the alternative that the variant holds. Theif constexprselects the code for each type at compile time.- The cases of a
std::variantare types, not names. A sum with two cases of the same type needs a wrapper struct for each case.
import java.util.ArrayList;
import java.util.List;
public class Main {
enum Light { RED, AMBER, GREEN }
// Product: a flag AND a light.
record Pair(boolean flag, Light light) {}
// Sum: a flag OR a light.
sealed interface Choice permits Flag, Lamp {}
record Flag(boolean flag) implements Choice {}
record Lamp(Light light) implements Choice {}
static String yn(boolean b) {
return b ? "yes" : "no";
}
static String name(Light l) {
return l.name().toLowerCase();
}
static String show(Choice c) {
return switch (c) {
case Flag f -> "flag:" + yn(f.flag());
case Lamp l -> "light:" + name(l.light());
};
}
public static void main(String[] args) {
boolean[] flags = {false, true};
List<Pair> pairs = new ArrayList<>();
List<Choice> choices = new ArrayList<>();
for (boolean f : flags) {
for (Light l : Light.values()) {
pairs.add(new Pair(f, l));
}
choices.add(new Flag(f));
}
for (Light l : Light.values()) {
choices.add(new Lamp(l));
}
System.out.println("pairs: " + pairs.size());
List<String> p = new ArrayList<>();
for (Pair pair : pairs) {
p.add(yn(pair.flag()) + "/" + name(pair.light()));
}
System.out.println(String.join(" ", p));
System.out.println("choices: " + choices.size());
System.out.println(String.join(" ", choices.stream().map(Main::show).toList()));
}
}
pairs: 6
no/red no/amber no/green yes/red yes/amber yes/green
choices: 5
flag:no flag:yes light:red light:amber light:green
- Verdict: native. A
recordis a product. Asealedinterface whose permitted subclasses are records is a sum of products. - The
switchinshowhas nodefault. The compiler accepts it becauseChoicepermits onlyFlagandLamp.
#include <stdbool.h>
#include <stdio.h>
enum light { RED, AMBER, GREEN };
static const char *light_name[] = { "red", "amber", "green" };
/* Product: a flag AND a light. */
struct pair {
bool flag;
enum light light;
};
/* Sum: a flag OR a light. The tag records which member of the union holds a value. */
enum choice_tag { FLAG, LAMP };
struct choice {
enum choice_tag tag;
union {
bool flag;
enum light light;
} as;
};
static const char *yn(bool b) { return b ? "yes" : "no"; }
int main(void) {
struct pair pairs[2 * 3];
struct choice choices[2 + 3];
int np = 0, nc = 0;
for (int f = 0; f < 2; f++) {
for (enum light l = RED; l <= GREEN; l++) {
pairs[np++] = (struct pair){ .flag = f, .light = l };
}
choices[nc++] = (struct choice){ .tag = FLAG, .as.flag = f };
}
for (enum light l = RED; l <= GREEN; l++) {
choices[nc++] = (struct choice){ .tag = LAMP, .as.light = l };
}
printf("pairs: %d\n", np);
for (int i = 0; i < np; i++) {
printf("%s%s/%s", i ? " " : "", yn(pairs[i].flag), light_name[pairs[i].light]);
}
printf("\nchoices: %d\n", nc);
for (int i = 0; i < nc; i++) {
printf("%s", i ? " " : "");
switch (choices[i].tag) {
case FLAG:
printf("flag:%s", yn(choices[i].as.flag));
break;
case LAMP:
printf("light:%s", light_name[choices[i].as.light]);
break;
}
}
printf("\n");
return 0;
}
pairs: 6
no/red no/amber no/green yes/red yes/amber yes/green
choices: 5
flag:no flag:yes light:red light:amber light:green
- Verdict: idiom. A
structis a product. Astructwith anenumtag and aunionis a sum. - Nothing ties the tag to the member of the union. The program must set and test the tag itself.
- The arrays have the sizes 2 × 3 and 2 + 3, the counts of the product and the sum.
bool[] flags = { false, true };
Light[] lights = Enum.GetValues<Light>();
var pairs = new List<Pair>();
var choices = new List<Choice>();
foreach (bool f in flags)
{
foreach (Light l in lights)
{
pairs.Add(new Pair(f, l));
}
choices.Add(new FlagCase(f));
}
foreach (Light l in lights)
{
choices.Add(new LampCase(l));
}
Console.WriteLine("pairs: " + pairs.Count);
Console.WriteLine(string.Join(" ", pairs.Select(p => Yn(p.Flag) + "/" + Name(p.Light))));
Console.WriteLine("choices: " + choices.Count);
Console.WriteLine(string.Join(" ", choices.Select(Show)));
static string Yn(bool b) => b ? "yes" : "no";
static string Name(Light l) => l.ToString().ToLowerInvariant();
static string Show(Choice c) => c switch
{
FlagCase f => "flag:" + Yn(f.Flag),
LampCase l => "light:" + Name(l.Light),
_ => throw new ArgumentException("unknown case"),
};
enum Light { Red, Amber, Green }
// Product: a flag AND a light.
record Pair(bool Flag, Light Light);
// Sum: a flag OR a light.
abstract record Choice;
sealed record FlagCase(bool Flag) : Choice;
sealed record LampCase(Light Light) : Choice;
pairs: 6
no/red no/amber no/green yes/red yes/amber yes/green
choices: 5
flag:no flag:yes light:red light:amber light:green
- Verdict: idiom. A
recordis a product. An abstract record with sealed records as its cases stands for a sum. - Other code can derive one more record from
Choice, so theswitchneeds the discard arm_. Without it, the compiler gives a warning.
const lights = ["red", "amber", "green"];
const flags = [false, true];
const yn = (b) => (b ? "yes" : "no");
// Product: an object with a flag AND a light.
const pairs = flags.flatMap((flag) => lights.map((light) => ({ flag, light })));
// Sum: an object with a kind field that says which case it is.
const choices = [
...flags.map((flag) => ({ kind: "flag", flag })),
...lights.map((light) => ({ kind: "light", light })),
];
function show(c) {
switch (c.kind) {
case "flag":
return "flag:" + yn(c.flag);
case "light":
return "light:" + c.light;
default:
throw new Error("unknown kind " + c.kind);
}
}
console.log("pairs: " + pairs.length);
console.log(pairs.map((p) => yn(p.flag) + "/" + p.light).join(" "));
console.log("choices: " + choices.length);
console.log(choices.map(show).join(" "));
pairs: 6
no/red no/amber no/green yes/red yes/amber yes/green
choices: 5
flag:no flag:yes light:red light:amber light:green
- Verdict: idiom. An object is a product. An object with a
kindfield is a sum by convention only. - Nothing checks the cases. The
defaultbranch that throws makes a wrongkindfail at once.
type Light = "red" | "amber" | "green";
const lights: Light[] = ["red", "amber", "green"];
const flags = [false, true];
// Product: a flag AND a light.
type Pair = { flag: boolean; light: Light };
// Sum: a flag OR a light. The kind field is the discriminant.
type Choice = { kind: "flag"; flag: boolean } | { kind: "light"; light: Light };
const yn = (b: boolean): string => (b ? "yes" : "no");
function show(c: Choice): string {
switch (c.kind) {
case "flag":
return "flag:" + yn(c.flag);
case "light":
return "light:" + c.light;
}
}
const pairs: Pair[] = flags.flatMap((flag) => lights.map((light) => ({ flag, light })));
const choices: Choice[] = [
...flags.map((flag): Choice => ({ kind: "flag", flag })),
...lights.map((light): Choice => ({ kind: "light", light })),
];
console.log("pairs: " + pairs.length);
console.log(pairs.map((p) => yn(p.flag) + "/" + p.light).join(" "));
console.log("choices: " + choices.length);
console.log(choices.map(show).join(" "));
pairs: 6
no/red no/amber no/green yes/red yes/amber yes/green
choices: 5
flag:no flag:yes light:red light:amber light:green
- Verdict: native. An object type is a product, and a union of object types with a common literal
kindfield is a discriminated union, a sum. - Inside
case "flag", the type checker narrowscto the flag case, soc.lightthere is a type error. showneeds no finalreturn, because the two cases cover the union.
package main
import (
"fmt"
"strings"
)
type Light int
const (
Red Light = iota
Amber
Green
)
var lights = []Light{Red, Amber, Green}
func (l Light) String() string {
return [...]string{"red", "amber", "green"}[l]
}
// Product: a flag AND a light.
type Pair struct {
Flag bool
Light Light
}
// Sum: a flag OR a light. The unexported method closes the set of cases.
type Choice interface{ isChoice() }
type Flag struct{ Flag bool }
type Lamp struct{ Light Light }
func (Flag) isChoice() {}
func (Lamp) isChoice() {}
func yn(b bool) string {
if b {
return "yes"
}
return "no"
}
func show(c Choice) string {
switch c := c.(type) {
case Flag:
return "flag:" + yn(c.Flag)
case Lamp:
return "light:" + c.Light.String()
}
panic("unknown case")
}
func main() {
flags := []bool{false, true}
var pairs []Pair
var choices []Choice
for _, f := range flags {
for _, l := range lights {
pairs = append(pairs, Pair{f, l})
}
choices = append(choices, Flag{f})
}
for _, l := range lights {
choices = append(choices, Lamp{l})
}
fmt.Println("pairs:", len(pairs))
var p []string
for _, pair := range pairs {
p = append(p, yn(pair.Flag)+"/"+pair.Light.String())
}
fmt.Println(strings.Join(p, " "))
fmt.Println("choices:", len(choices))
var c []string
for _, choice := range choices {
c = append(c, show(choice))
}
fmt.Println(strings.Join(c, " "))
}
pairs: 6
no/red no/amber no/green yes/red yes/amber yes/green
choices: 5
flag:no flag:yes light:red light:amber light:green
- Verdict: idiom. A
structis a product. Go has no sum types, so an interface with an unexported method and a type switch stand for one. - The type switch does not check that it covers every case. The
panicat the end makes a missing case fail at once.
#[derive(Clone, Copy)]
enum Light {
Red,
Amber,
Green,
}
const LIGHTS: [Light; 3] = [Light::Red, Light::Amber, Light::Green];
// Product: a flag AND a light.
struct Pair {
flag: bool,
light: Light,
}
// Sum: a flag OR a light.
enum Choice {
Flag(bool),
Light(Light),
}
fn name(l: Light) -> &'static str {
match l {
Light::Red => "red",
Light::Amber => "amber",
Light::Green => "green",
}
}
fn yn(b: bool) -> &'static str {
if b { "yes" } else { "no" }
}
fn show(c: &Choice) -> String {
match c {
Choice::Flag(f) => format!("flag:{}", yn(*f)),
Choice::Light(l) => format!("light:{}", name(*l)),
}
}
fn main() {
let flags = [false, true];
let mut pairs = Vec::new();
for &flag in &flags {
for &light in &LIGHTS {
pairs.push(Pair { flag, light });
}
}
let mut choices: Vec<Choice> = flags.iter().map(|&f| Choice::Flag(f)).collect();
choices.extend(LIGHTS.iter().map(|&l| Choice::Light(l)));
println!("pairs: {}", pairs.len());
let p: Vec<String> = pairs.iter().map(|p| format!("{}/{}", yn(p.flag), name(p.light))).collect();
println!("{}", p.join(" "));
println!("choices: {}", choices.len());
let c: Vec<String> = choices.iter().map(show).collect();
println!("{}", c.join(" "));
}
pairs: 6
no/red no/amber no/green yes/red yes/amber yes/green
choices: 5
flag:no flag:yes light:red light:amber light:green
- Verdict: native. A
structis a product, and anenumwhose variants carry data is a sum. - A
matchoverChoicemust cover both variants, or the program does not compile. Lightis anenumwhose variants carry no data, so it is an enumeration.
Variations and related ideas
- Product types. Records, structs and tuples. See Product type, Record type and Tuple.
- Sum types. Tagged unions, variants and sealed hierarchies. See Sum types.
- Enumerations. A sum whose cases carry no data. See Enumeration.
- Option and result types.
Maybe ain Haskell andOption<T>in Rust are sums with a case for no value. They replace the null reference. See Null reference. - Generalized algebraic data types. A GADT lets each constructor give a more specific result type. Scala 3 enums support "algebraic data types (ADTs) and their generalized version (GADTs)".21 See generalized-algebraic-data-type.
- Row polymorphism and open variants. Some languages let a record or a variant have more fields or more cases than a function names. See Row polymorphism.
- Untagged unions. A union type with no tag, such as
int | strin Python, is not the same as a sum. See Union type.
Pitfalls
An abstract data type is not an algebraic data type
Both names are shortened to ADT, but they are different ideas. An abstract data type is "defined by its behavior (semantics) from the point of view of a user of the data".22 A stack is defined by push and pop, and its representation is hidden. An algebraic data type is the opposite. Its representation is the definition: the cases and the fields are public, and the code matches on them. The Wikipedia article on algebraic data types starts with the note "Not to be confused with Abstract data type."1 See Abstract data type.
A product where a sum is needed
A record with a flag for each state is a product, so it can hold every combination of the flags. Some of the combinations have no meaning. Here a request has a flag loading, an optional error and an optional data. That is 2 × 2 × 2 = 8 combinations of set and not set, but a request has only 3 real states.
This code runs but gives a wrong answer on purpose.
from dataclasses import dataclass
@dataclass
class Request:
loading: bool
error: str | None
data: str | None
r = Request(loading=True, error="timeout", data="partial")
print("loading and failed at the same time:", r.loading and r.error is not None)
loading and failed at the same time: True
The constructor accepts this value, and each reader must decide what it means. The fix is a sum of three cases, Loading, Failed(error) and Loaded(data). The sum has exactly the 3 legal states. See Make illegal states unrepresentable.
A sum that a language cannot close
In Python, TypeScript and JavaScript, the cases of a union exist only in the type checker, or only in the program's convention. In C# and Go, any code can add one more class or one more type that implements the interface. In these languages, a new case does not stop the build. Sum types shows the missing case in each language, and how to make it fail early.
Cost
A value of a product has all of its fields, and a value of a sum has one case and a tag. Construction allocates the value once. A match reads the tag and selects a branch, which is usually a jump through a table or a short chain of tests. In C, the size of a union is the size of its largest member,6 so a sum of a small case and a large case uses the large size for every value. Languages that store each case as an object on the heap, such as Java, C#, Kotlin and Python, add an allocation and a reference for each value.
History
Algebraic types "first appeared in Burstall's NPL (Burstall, 1977) and Burstall, MacQueen, and Sannella's Hope (Burstall et al., 1980)".2 At the first Lisp conference, in August 1980, Burstall, MacQueen and Sannella presented "Hope, the language that introduced algebraic data types".2 Algebraic types "were absent from the original ML (Gordon et al., 1979) and KRC (Turner, 1982), but appeared in their successors Standard ML (Milner et al., 1997) and Miranda (Turner, 1986)".2 Hope and Standard ML kept sums and products apart: a branch of a tree took one argument, a tuple of two trees. Haskell took the sum of products form from Miranda, so a constructor takes several fields.2
Mainstream languages added the two parts later. Java added records in Java 16 and sealed classes in Java 17.1 JEP 409 says that the combination "is sometimes referred to as algebraic data types".10 Rust (with enum), Swift, Kotlin, Scala and TypeScript all have the two operations.152016219
References
- Algebraic data type, Wikipedia, the introduction; Theory
- P. Hudak, J. Hughes, S. Peyton Jones and P. Wadler, A History of Haskell, Being Lazy With Class, HOPL III, 2007, 2.2 (the Lisp conference of August 1980); 5 Data types and pattern matching; 5.1 Algebraic types
- Joel Burget, The algebra (and calculus!) of algebraic data types, Code Words, issue 3, Counting inhabitants
- Unit type, Wikipedia, the introduction
- Haskell 2010 Language Report, chapter 4, Declarations and Bindings, 4.2.1 Algebraic Datatype Declarations
- ISO/IEC 9899:201x, committee draft N1570 (C11), 6.2.5p20 (structure and union types); 6.7.2.1p15 and p16 (padding; the size of a union)
- The Python Standard Library, dataclasses, the introduction
- The Python Standard Library, typing, typing.Union
- TypeScript Handbook, Narrowing, Discriminated unions
- JEP 409: Sealed Classes, Sealing and record classes
- Working Draft, Standard for Programming Language C++ (N4950), [tuple.general], 22.4.1 In general
- Working Draft, Standard for Programming Language C++ (N4950), [variant.variant.general], 22.6.3.1 General
- C# fundamentals, Record types, the introduction
- Go FAQ, Why does Go not have variant types?, the answer
- The Rust Programming Language, 6.1 Defining an Enum, the introduction
- Kotlin documentation, Sealed classes and interfaces, the introduction
- The OCaml Manual, release 5.3, Type and exception definitions, Type definitions
- F# language reference, Discriminated Unions, Remarks
- F# language reference, Records, Remarks
- The Swift Programming Language, Enumerations, the introduction; Associated Values
- Scala 3 Reference, Algebraic Data Types, the introduction
- Abstract data type, Wikipedia, the introduction
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag ET4237 Edit this page History Report an error Markdown