Pattern Matching Function Clauses
Pattern Matching with Multiple Function Clauses
Welcome. In this course on advanced pattern matching in Elixir, we start by using multiple function clauses to route different inputs to the correct logic. If you are new to this idea, think of it as matching the “shape” of data right in the function head. This builds on core Elixir fundamentals and prepares you for later topics like guards, case statements, and the pin operator.
Walkthrough: A Calculator Using Function Clauses
Explanation:
- defmodule Calculator do … end defines a module named Calculator.
- Multiple def calculate clauses each match a different tuple pattern:
- {:add, a, b} returns a + b
- {:subtract, a, b} returns a - b
- {:multiply, a, b} returns a * b
- Division is handled with two clauses:
- {:divide, a, b} when b != 0 uses a guard to ensure b is not zero, then returns a / b.
- {:divide, _a, 0} matches divide-by-zero and returns an error tuple. The underscore in _a means “ignore this value.”
- Order matters. Elixir picks the first clause whose pattern matches and whose guard (if any) evaluates to true.
- The last three lines run the function:
- IO.puts prints the results of addition (8) and multiplication (28).
- IO.inspect prints the error tuple {:error, "Cannot divide by zero"} in a readable form.
This approach keeps the logic simple and readable. Instead of one function with many if/else statements, each operation becomes a clear, separate clause that matches a specific input shape.
Beyond Tuples: Matching Lists, Maps, Structs, and Binaries
Pattern matching in function heads is not limited to tuples. You can match on lists, maps, structs, and binaries, allowing for highly expressive and safe APIs.
Matching Lists
Explanation:
- The base case
sum([])matches an empty list and returns 0, stopping recursion. - The recursive case
sum([head | tail])uses the[head | tail]pattern to split a non-empty list.headis the first element, andtailis the rest of the list. - This pattern is the standard way to traverse and process collections in functional programming.
