Course contentsShow
← Computer Science
Lesson 2141 of 2,87248. Programming ParadigmsFree lesson

Pattern Matching

Destructure and handle different data cases elegantly with pattern matching syntax.

Pattern Matching

You'll learn how to destructure data and handle different cases elegantly using pattern matching syntax.

What is Pattern Matching?

Pattern matching is a powerful control-flow mechanism that lets you inspect the structure and shape of data, extracting values while simultaneously checking which variant or case you're dealing with. Unlike a chain of if-else statements that test conditions, pattern matching declares what shape the data should have and automatically binds names to the parts you care about.

Think of it like a sophisticated vending machine sorting system: instead of manually checking "Is it a coin? What size? What metal?", you drop items into shaped slots—each slot's shape is the test, and items that fit trigger specific handling.

How It Works with Algebraic Data Types

Pattern matching shines when working with algebraic data types (ADTs). Remember that ADTs let you define types as combinations of variants—like a Shape being either a Circle(radius) or Rectangle(width, height). Pattern matching lets you branch on which variant you have while simultaneously extracting the data inside:

match shape:
  Circle(r) -> area = π * r²
  Rectangle(w, h) -> area = w * h

In one elegant expression, you've checked the type, extracted the fields, and computed the result.

Key Benefits

  • Exhaustiveness checking: The compiler ensures you've handled all possible cases
  • Destructuring: Extract nested data in one step instead of multiple accessor calls
  • Readability: The code's structure mirrors the data's structure
  • Safety: No forgotten cases, no null checks scattered everywhere

Key Takeaway: Pattern matching combines type checking, destructuring, and control flow into a single expressive construct that makes working with structured data safer and more elegant than imperative conditionals.