Algebraic data type

Also known as: ADT

On this page 7

An algebraic data type (ADT) is a composite type formed by combining other types with two operations: product types, which hold several values at once, and sum types, which hold exactly one of several alternatives. In functional programming, algebraic data types are the primary way to describe the shape of data, and together with pattern matching they let the compiler verify that every possible case is handled.

The name comes from the fact that the number of possible values of such a type follows ordinary algebra: a product multiplies the counts of its components, and a sum adds them. Languages such as Haskell, OCaml, F#, Scala, Rust, Swift and Elm support ADTs directly, and TypeScript and modern Java emulate them. The acronym should not be confused with abstract data type, which describes a type by its operations rather than its structure.

How product and sum types combine

A product type groups fields that all exist together, like a tuple or record. A point with an x and a y coordinate is a product: every value contains both. A sum type, also called a tagged union, variant or discriminated union, contains one value chosen from a fixed set of constructors, each optionally carrying its own data.

In Haskell, data Shape = Circle Double | Rect Double Double defines a sum of two constructors, where Rect is itself a product of two numbers. At run time each value carries a tag identifying its constructor, which pattern matching inspects to select the correct branch.

The table below shows how the two building blocks relate to familiar constructs and to the cardinality arithmetic behind the name.

KindMeaningCardinality ruleFamiliar equivalents
Product typeAll fields present togetherMultiply component countsTuple, record, struct
Sum typeExactly one alternative presentAdd alternative countsTagged union, enum with data
Unit typeSingle possible valueEquals 1Empty tuple, void-like value
Empty typeNo possible valueEquals 0Never, Void, bottom type
Product and sum types side by side

For example, a pair of a Boolean and a three-valued enum has 2 × 3 = 6 values, while a sum of the same two types has 2 + 3 = 5 values. This arithmetic is not merely a curiosity: it explains why type isomorphisms hold and why function types correspond to exponentiation.

Common algebraic data types in functional programming

A handful of standard ADTs appear in nearly every functional codebase, and many of them are recursive, meaning a constructor refers to the type being defined. Recursion lets a finite definition describe unbounded structures such as lists and trees.

TypeDefinition sketchPurpose
Option or MaybeNone, or Some of a valueRepresents an absent value without null
Either or ResultLeft error, or Right successRepresents failure as ordinary data
ListEmpty, or element plus listRecursive sequence of values
Binary treeLeaf, or node with two subtreesHierarchical data and search trees
Expression treeLiteral, addition, multiplicationAbstract syntax for interpreters
Widely used algebraic data types

The Option type is the best-known example of how ADTs replace error-prone conventions. Instead of returning a null reference, which Tony Hoare later called his billion-dollar mistake, a function returns a value whose type forces the caller to handle the empty case explicitly. Result types play the same role for errors and are used in Rust instead of exceptions.

ADTs can also be parameterized by other types, as in Maybe a or Result<T, E>, and generalized algebraic data types (GADTs) refine this further by letting each constructor specify a more precise return type, which enables type-safe interpreters.

Pattern matching and exhaustiveness checking

Algebraic data types are consumed through pattern matching, a construct that inspects a value’s constructor and binds its fields to names in a single step. Because the set of constructors in a sum type is closed and known at compile time, the compiler can perform exhaustiveness checking and warn when a case is missing.

This property makes refactoring markedly safer. When a developer adds a new constructor, for instance a Triangle variant to Shape, every match that does not handle it is reported, turning a potential runtime defect into a compile-time error. Rust treats non-exhaustive matches as hard errors, while Haskell and OCaml issue warnings that teams usually promote to errors.

Pattern matching also supports nested patterns, guards and wildcards, so complex structural conditions can be expressed declaratively. Recursive functions over ADTs often follow the structure of the type exactly, a technique known as structural recursion, which generalizes to the fold operation.

Algebraic data types overlap with several constructs found in other paradigms, but they differ in safety guarantees and extensibility. The comparison below highlights the distinctions practitioners most often need.

ConstructClosed set of casesCarries data per caseExhaustiveness checked
Algebraic data typeYesYesYes, by compiler
Plain enumerationYesNoOften, by compiler
C unionYesYes, untaggedNo
Class hierarchyNo, open to subclassesYesOnly with sealed classes
Abstract data typeNot applicableHidden behind operationsNot applicable
ADTs compared with neighboring constructs

The contrast with class hierarchies illustrates the expression problem. With ADTs, adding a new operation means writing one new function, but adding a new case requires updating every existing function. Object-oriented hierarchies reverse the trade. Java’s sealed interfaces with records and Kotlin’s sealed classes bring the closed-world model of ADTs into object-oriented languages.

Designing with algebraic data types

The central design guideline is to make illegal states unrepresentable. Instead of a record with a status flag and several optional fields that are only valid in certain states, a developer defines a sum type with one constructor per state, each carrying exactly the fields that state needs.

SituationRecommended choiceReason
Value may be missingOption typeForces handling of absence
Operation may failResult or Either typeMakes errors explicit in signatures
Mutually exclusive statesSum type, one constructor eachRemoves invalid flag combinations
Many cases added over time by pluginsInterface or type classSum types are closed to extension
Design decisions when modeling with ADTs
  • Avoid boolean blindness: a two-constructor type with meaningful names reads better than true and false.
  • Keep sum types reasonably small; dozens of constructors often signal a missing abstraction.
  • Watch memory layout: a sum type typically occupies the size of its largest variant plus a tag.

The main limitation is that ADTs are closed by design, so libraries cannot let users add new cases without changing the original definition. Languages address this with open variants in OCaml or with type classes, each at some cost in static guarantees.

A plain-language summary

An algebraic data type is a way of describing exactly what shapes your data can take. Some data is made of several parts that always come together, like a street address with a street, a city and a postal code. Other data is one choice out of a short list, like a parcel that is either waiting, in transit or delivered.

Algebraic data types let a programmer write both kinds down precisely. The computer then checks that the program handles every possible choice, much like a checklist that will not let you sign off until every box is ticked.

An example from practice

A team building a payment service in Rust models the state of each transaction as a sum type with four variants: Pending with a creation time, Authorized with an authorization code, Settled with a settlement date and amount, and Failed with an error reason. Previously the same data lived in one record with a status string and five optional fields, and support tickets regularly traced back to records marked settled but missing an amount.

After the change, a settled transaction cannot exist without its amount, because the type has nowhere to omit it. Later, when the business introduced partial refunds, developers added a Refunded variant and the compiler immediately listed eleven match expressions that needed updating. The team fixed each one before release, and the class of inconsistent-record defects disappeared from the incident log.