Course contentsShow
← Computer Science
Lesson 1988 of 2,87245. Type Systems and SemanticsFree lesson

Composite Types: Sums

Learning sum types (unions, enums, variants) that represent a value being one of several possible types.

Composite Types: Sums

You'll learn how sum types let a value be "one of several possible types" rather than "all types at once."

The Core Idea

While product types (like tuples or structs) combine multiple values together simultaneously, sum types represent a choice between alternatives. A value of a sum type holds exactly one variant from a fixed set of possibilities.

Think of it like a union ballot: you check exactly one box. The value might be an integer or a string or a boolean—but never two at once.

Common Names and Forms

Sum types appear under different names across languages:

  • Tagged unions or discriminated unions (C, C++)
  • Enums or algebraic data types (Rust, Haskell, ML)
  • Variant types (OCaml)
  • Union types (TypeScript, though less strict)

The key feature: the type system tracks which variant you're currently holding.

Why "Sum"?

In type theory, if type A has 3 possible values and type B has 5 possible values, a sum type A + B has 3 + 5 = 8 possible values. You get the sum of possibilities, whereas product types multiply them.

Analogy

Imagine a package delivery status. At any moment, a package is in one state:

  • InTransit(tracking_number)
  • Delivered(timestamp, signature)
  • Failed(error_message)

The package can't be both delivered and in transit. A sum type models this perfectly—one variant active at a time, each potentially carrying different associated data.

Key Takeaway: Sum types represent "one of several alternatives," allowing type-safe modeling of mutually exclusive possibilities, with the type system ensuring you handle each case correctly.