liveBook · Manning

Algebraic data type

As explained in Functional Programming in Scala, Second Edition

An algebraic data type is a data type defined as a sum of one or more data constructors, where each constructor is a product of its arguments.

An algebraic data type (ADT) defines a type through one or more data constructors. The type is a sum of constructor alternatives, while each constructor is a product of its arguments. section 3.4

In Scala, ADTs can use enumerations or sealed trait hierarchies. Constructors may take zero or more arguments, and pattern matching inspects the values used to construct them. section 3.6

A binary tree

A tree has two constructors: Leaf(value) stores a value, while Branch(left, right) combines two trees. A recursive size operation matches Leaf as the base case and Branch as the recursive case, computing 1 + size(left) + size(right). The same operation can be expressed as a method or a standalone function.

ADTs support several recurring functional-programming techniques:

  • Model lists with Cons(head, tail) and Nil, making the empty and nonempty cases explicit. section 3.6
  • Use exhaustive pattern matching to ensure that every constructor is handled; non-exhaustive matches may produce MatchError. section 3.6
  • Recurse over constructors to implement operations, then generalize repeated traversals with higher-order functions such as map, filter, flatMap, foldRight, and foldLeft. section 3.6
  • Represent success and failure as values with ADTs such as Option, Either, Try, and Validated instead of throwing exceptions. section 4.6

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Defines sums and products, demonstrates Scala encodings, and works through recursive tree and list operations without formal algebraic derivations.
Examples
Uses tuples, binary trees, singly linked lists, and error types including Option, Either, Try, and Validated.
What you can do after
Build immutable lists and trees, operate on their constructors with pattern matching, and represent errors as composable values.
How it connects
Connects ADTs with pattern matching, immutable data structures, recursion, pure functions, persistence, and higher-order functions.

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 Functional Programming in Scala, Second Edition. The section links point to the parts of the book it draws on.