liveBook · Manning

Algebraic data type

As explained in The Joy of JavaScript

A composite type formed by combining simpler types with sum and product structure to represent a finite set of possibilities.

An algebraic data type (ADT) is an immutable composite data structure with a well-known interface. It combines values into a meaningful shape and lets operations compose around that shape. Here, “type” describes an object's structure and behavior, not necessarily a statically checked type. section 5.5 section 1.3

Two common forms express different relationships:

  • A record, or product type, holds values that belong together: an immutable Pair might hold a username AND password. Unlike a plain array, it communicates their relationship. section 5.5.1
  • A choice, or sum type, represents one of several alternatives: success OR failure, never both. It gives validation and error handling explicit states instead of relying on a Boolean. section 5.5.2

The practical payoff is composition when an operation might fail. Repeated validation checks or try/catch blocks interrupt an ordinary function pipeline. A Validation choice can carry a successful value through mapped operations; on failure, later mapped operations are skipped while the error remains available. section 5.0 section 1.3 section 8.2.2

A composable validation chain

Validation.of(block).flatMap(checkLength(64)).flatMap(checkTampering).flatMap(checkDifficulty).flatMap(checkLinkage(previousHash)).flatMap(checkTimestamps(previousTimestamp)); Each check becomes a step in one chain rather than another layer of conditional control flow. section 5.0

Promises offer a related way to think about this pattern: after pending, a Promise settles as fulfilled or rejected, much as Validation represents success or failure. Promise.then composes work on the fulfilled path, while Promise.catch handles rejection. An algebraic data type is not the same thing as an abstract data type such as a Stack or Queue. section 8.2.2 section 5.5

How The Joy of JavaScript covers it

How deep it goes
Defines immutable composite types, distinguishes records from choices, and works through validation chains and a Promise analogy.
Examples
Uses an immutable Pair, success-or-failure validation, a blockchain-checking chain, and Promise states.
What it assumes
Assumes familiarity with JavaScript function composition and higher-order functions while introducing ADT fundamentals.
What you can do after
Build it from scratch as a Validation type and compose checks with flatMap instead of repeated branching.
How it connects
Connects product types and sum types to function composition, functors, monads, validation, and promises.

Also explained in

Compare how 5 books explain algebraic data type →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Joy of JavaScript. The section links point to the parts of the book it draws on.