Course contentsShow
← Computer Science
Lesson 2140 of 2,87248. Programming ParadigmsFree lesson

Algebraic Data Types

Define complex data structures using sum types and product types for type safety.

Algebraic Data Types

You'll learn how to define complex, type-safe data structures by combining sum types and product types.


In functional programming, algebraic data types (ADTs) give you a precise, mathematical way to model data. They combine two fundamental building blocks:

Product Types

A product type combines multiple values together—like a struct or tuple. It's called "product" because the total number of possible values is the product of each component's possibilities.

Think of it like ordering a meal: a combo has a burger AND fries AND a drink—all components must be present.

Sum Types

A sum type represents a choice between alternatives—one value OR another, but not both. It's called "sum" because the total possibilities is the sum of each variant's possibilities.

Like a payment method: you can pay with cash OR card OR cryptocurrency—pick exactly one.

Combining Them

Real-world data often needs both. Imagine modeling a shape:

Shape = Circle of radius
      | Rectangle of width and height
      | Triangle of side1, side2, side3

This is a sum type (one of three shape kinds) where each variant is a product type (bundling multiple measurements). The compiler enforces that you handle all cases—no forgotten shapes, no invalid combinations.

This approach eliminates entire classes of bugs. You can't accidentally treat a circle's radius as a rectangle's width, because the type system knows they're different variants. Every function processing shapes must explicitly handle each case.

Key Takeaway:
Algebraic data types combine product types (AND—bundling values) and sum types (OR—choosing variants) to create precise, compiler-verified data models that make invalid states unrepresentable.