Advanced Topic 41 of 50 Languages & Compilers
Algebraic Data Types
Types built from sums and products.
How it works
Algebraic data types build new types by combining others in two ways: product types, such as tuples and records, which hold several values together, and sum types, also called tagged unions or variants, which hold one of several alternatives, each possibly carrying data. For example, a shape can be a Circle with a radius or a Rectangle with width and height. Recursive definitions model lists and trees, and pattern matching takes values apart safely.
Step-by-step walkthrough
- A product type combines values: a pair holds both fields.
- A sum type is a choice of variants.
- A Shape is either a Circle or a Rectangle.
- The compiler knows all cases, so it can check you handled each.
- They model data precisely and make illegal states unrepresentable.
Where it is used
Haskell, OCaml, Rust enums, Swift enums, Kotlin sealed classes and TypeScript discriminated unions use them to model option values, results, abstract syntax trees, state machines and messages.
Common pitfall
Languages without sum types simulate them with inheritance or flags, losing exhaustiveness checking. Deeply nested types become hard to read. Adding a new variant requires updating all matches, which the compiler flags, a benefit. Make illegal states unrepresentable, prefer Option and Result over null and exceptions for expected cases and match exhaustively.
Where it fits in the course
Algebraic Data Types is topic 41 of 50 in Languages & Compilers, rated Advanced. It follows Type Systems. The next topic is Pattern Matching.
Practice and explore
- Open the interactive lesson, with a mini quiz.
- Take the Languages & Compilers quiz.
How to study this topic
- Read the explanation above and restate the definition in your own words.
- Open the interactive lesson and answer its mini quiz.
- Read the common pitfall, then write a short example that avoids it.
- Check your understanding in the Languages & Compilers quiz, and revisit the topic if you miss a question.
Frequently asked questions
What is Algebraic Data Types?
Where do people use Algebraic Data Types?
What is the most common mistake with Algebraic Data Types?
What should I learn before this topic?
How can I practice it?
Is Algebraic Data Types hard to learn?
How long does it take to learn Algebraic Data Types?
Which topics are related to Algebraic Data Types?
What should I study after Algebraic Data Types?
Related topics
- Type Systems (Languages & Compilers)
- Pattern Matching (Languages & Compilers)
- LLVM (Languages & Compilers)
- Ownership and Borrowing (Languages & Compilers)
- Data Types (Programming Fundamentals)
- Data Types in SQL (Databases)
- Open Data and Licensing (Emerging & Frontier Topics)