liveBook · Manning

Pattern matching

As explained in Functional Design and Architecture: Examples in Haskell

Pattern matching is a language mechanism that selects behavior by matching a value against structural patterns and binding its components.

Pattern matching selects behavior by inspecting a value’s structure, extracting its components, and applying the matching branch. With a typed Shape value, separate Circle and Rectangle cases make each area calculation explicit. section 1.5.2

Calculating a shape’s area

A pattern-matching definition keeps the data cases visible: area (Circle r) = pi * r^2; area (Rectangle w h) = w * h. Calling area with an integer fails at compile time because the function requires Shape, avoiding a debugger-driven failure. section 1.5.2

Pattern matching also handles effectful or optional results. Nested case expressions over Maybe values propagate Nothing explicitly, but the same matching behavior can be hidden inside the Maybe monad and expressed with concise do notation. section 1.5.4

Free interpreters use the same technique recursively: match the Free constructor, descend through its continuation, match each domain constructor, perform its action, and stop at Pure. section 6.3.5

How Functional Design and Architecture: Examples in Haskell covers it

How deep it goes
Explains extraction, typed rejection, nested Maybe cases, and recursive Free interpretation, but defers formal matching semantics.
Examples
Demonstrates Shape area calculation, nested Maybe lookups, do notation, and a SandwichRecipe free interpreter.
What it assumes
Assumes basic typed functional definitions and introduces constructor-based data cases through Shape and Maybe examples.
What you can do after
Apply it via Haskell definitions to branch on data constructors, extract fields, and process recursive interpreter structures.
How it connects
Connects pattern matching to strong static type systems, type-level design, Maybe, monads, free monads, and interpreters.

Also explained in

Compare how 12 books explain pattern matching →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Functional Design and Architecture: Examples in Haskell. The section links point to the parts of the book it draws on.