Programming Search⌘K

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))
Output
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

LanguageVerdictNote
PythonIdiom
C++Standard library
JavaNative
CIdiom
C#Idiom
JavaScriptIdiom
TypeScriptNative
GoIdiom
RustNative
KotlinNativeA 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.
SQLIdiomA 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.
BashDoes not applyBash 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.
PowerShellAbsentPowerShell 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.
HTMLDoes not applyMarkup has no types.
CSSDoes not applyStyle rules have no types.
Regular expressionsDoes not applyA 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

PythonGitHub
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))
Output
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 dataclass is a product. A union of classes, Flag | Lamp, is a sum, and match selects 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 show then returns None.
  • itertools.product builds 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";
}
Output
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::pair and std::tuple are products, and std::variant is a sum.
  • std::visit calls the lambda with the alternative that the variant holds. The if constexpr selects the code for each type at compile time.
  • The cases of a std::variant are types, not names. A sum with two cases of the same type needs a wrapper struct for each case.
JavaGitHub
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()));
    }
}
Output
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 record is a product. A sealed interface whose permitted subclasses are records is a sum of products.
  • The switch in show has no default. The compiler accepts it because Choice permits only Flag and Lamp.
#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;
}
Output
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 struct is a product. A struct with an enum tag and a union is 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;
Output
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 record is 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 the switch needs the discard arm _. Without it, the compiler gives a warning.
JavaScriptGitHub
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(" "));
Output
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 kind field is a sum by convention only.
  • Nothing checks the cases. The default branch that throws makes a wrong kind fail at once.
TypeScriptGitHub
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(" "));
Output
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 kind field is a discriminated union, a sum.
  • Inside case "flag", the type checker narrows c to the flag case, so c.light there is a type error.
  • show needs no final return, 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, " "))
}
Output
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 struct is 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 panic at the end makes a missing case fail at once.
RustGitHub
#[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(" "));
}
Output
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 struct is a product, and an enum whose variants carry data is a sum.
  • A match over Choice must cover both variants, or the program does not compile.
  • Light is an enum whose variants carry no data, so it is an enumeration.
  • 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 a in Haskell and Option<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 | str in 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)
Output
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

  1. Algebraic data type, Wikipedia, the introduction; Theory
  2. 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
  3. Joel Burget, The algebra (and calculus!) of algebraic data types, Code Words, issue 3, Counting inhabitants
  4. Unit type, Wikipedia, the introduction
  5. Haskell 2010 Language Report, chapter 4, Declarations and Bindings, 4.2.1 Algebraic Datatype Declarations
  6. 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)
  7. The Python Standard Library, dataclasses, the introduction
  8. The Python Standard Library, typing, typing.Union
  9. TypeScript Handbook, Narrowing, Discriminated unions
  10. JEP 409: Sealed Classes, Sealing and record classes
  11. Working Draft, Standard for Programming Language C++ (N4950), [tuple.general], 22.4.1 In general
  12. Working Draft, Standard for Programming Language C++ (N4950), [variant.variant.general], 22.6.3.1 General
  13. C# fundamentals, Record types, the introduction
  14. Go FAQ, Why does Go not have variant types?, the answer
  15. The Rust Programming Language, 6.1 Defining an Enum, the introduction
  16. Kotlin documentation, Sealed classes and interfaces, the introduction
  17. The OCaml Manual, release 5.3, Type and exception definitions, Type definitions
  18. F# language reference, Discriminated Unions, Remarks
  19. F# language reference, Records, Remarks
  20. The Swift Programming Language, Enumerations, the introduction; Associated Values
  21. Scala 3 Reference, Algebraic Data Types, the introduction
  22. 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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/ET4237/text.yaml