Definition
A sum type (or coproduct) is a Type Constructor that represents a choice between two or more types. Given types and , their sum consists of values that come from either or , tagged to indicate their origin.
More generally, the sum of types is written and contains values from any of these types, each tagged with its index.
Type Rules
Sum types are characterized by their introduction and elimination rules:
Introduction Rules
We can inject a value from into the sum using (inject left) or a value from using (inject right).
Elimination Rule
To use a sum type, we must handle both cases: provide functions for both possible types and perform case analysis.
Computation Rules (β-rules)
Eta Rule (η-rule)
For any :
Category-Theoretic View
In category theory, the sum type corresponds to the categorical coproduct. The type is the coproduct of and with injection morphisms and .
The coproduct satisfies a universal property: for any type with morphisms and , there exists a unique morphism such that and .
Examples
Common sum types in programming languages:
- : Boolean as sum of two unit types
- : Optional values
- : Explicit sum type in functional languages
- : Success or error values
Duality with Product Types
Sum types are dual to product types:
- Product types use conjunction ( and ), sum types use disjunction ( or )
- Product introduction requires both components, sum introduction requires one component
- Product elimination extracts one component, sum elimination must handle both cases
- In logic: product corresponds to conjunction (), sum corresponds to disjunction ()
Related Concepts
- Dependent Sum: A generalization where types may depend on values
- Type Constructor: Sum types as a fundamental type constructor
- Introduction Rule: The injection operations for sum types
- Elimination Rule: Case analysis on sum types
- Function Type: Related by exponential laws
- Existential: A propositionally truncated sum type.