Pattern Matching
Table of Contents
Pattern Matching
Pattern matching is a declarative mechanism in programming for checking a value against a specific structure or "pattern". If the value conforms to the pattern, the match is successful, and the process can destructure the value, binding parts of it to variables.
It is a core feature in many Functional Programming languages and is increasingly being adopted by others due to its expressiveness and power.
The Match Operator vs. Assignment
In many languages that feature pattern matching, like Elixir, the = symbol is a match operator, not an assignment operator.
- Assignment (= in imperative languages) tells the system to assign the value on the right to the variable on the left.
- Matching (= in Elixir) is an assertion. It asserts that the expression on the left matches the expression on the right. If the match is possible, any unbound variables on the left are bound to the corresponding values from the right. If it's not possible, a match error is raised.
For example: x = 1 will bind 1 to x. However, 1 = x will also succeed, binding 1 to x. But 1 = 2 will fail because it's an impossible assertion.
Core Use Cases & Examples
Pattern matching excels at making code more readable and concise compared to traditional conditional logic, such as nested if-else or switch statements.
- Destructuring Data Structures: It's a powerful mechanism for extracting values from complex data types like tuples, lists, and maps.
Tuples: Often used for function return values to indicate success or failure.
# Successful database call {:ok, user} = Db.get_user(123) # Now the 'user' variable is bound and can be used. # A failed call might return a different tuple {:error, :not_found} = Db.get_user(999)Lists: Commonly used in recursive functions to process a list head and tail separately.
def sum_list([]), do: 0 def sum_list([head | tail]), do: head + sum_list(tail)
Function Clause Selection: It can be used in function heads to control program flow by executing different function clauses based on the shape or value of the input data. This is a form of function overloading.
def handle_request("GET", path) do # logic for GET requests end def handle_request("POST", path) do # logic for POST requests end def handle_request(_, _) do # fallback for other methods endThe case Statement: Provides a way to match a value against several patterns until a match is found, executing the code associated with that pattern.
case File.read("my_file.txt") do {:ok, content} -> IO.puts("File content: #{content}") {:error, reason} -> IO.puts("Error reading file: #{reason}") end
Benefits of Pattern Matching
- Readability & Conciseness: It clearly expresses the expected structure of data, reducing the need for verbose conditional checks.
- Immutability: It pairs naturally with immutable data structures. Since data isn't modified in place, you match on its current shape and create new data structures from the bound variables.
- Exhaustiveness Checking: In statically-typed languages like Rust and Haskell, the compiler can warn you if your patterns don't cover all possible cases (e.g., for an enum), preventing potential runtime errors.
- Declarative Style: You declare what the data should look like, rather than writing imperative code to inspect and extract values from it.