Chapter 5

Pattern Matching and Algebraic Data Types

Most functional programming languages—as well as many of the hybrid languages that aspire to support functional programming—define a form of pattern matching. Pattern matching has many uses, from a simple switch-like construct to runtime type checking and casting, but it is most effective when applied to algebraic data types, which combine alternatives and aggregation.

5.1 Functional Switch

As a starting point, you can think of pattern matching as a form of functional switch. For instance, the earlier example using if-then-else

Scala

val verbosity = if arg == "-v" then 1 else if arg == "-vv" then 2 else 0

could be rewritten to use pattern matching instead:

Get Functional and Concurrent Programming: Core Concepts and Features now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.