Pattern Matching with Case
Pattern Matching in 'case' Statements
Welcome back. In the last lesson, you added guard clauses to function heads. As a reminder, guards let you attach extra conditions to a match. Today, you will use the same ideas inside a case expression. This gives you clean, readable branching based on data shape at runtime.
Classifying Users with 'case'
Explanation:
case user dotries each clause from top to bottom and picks the first match.%{name: name, age: age, role: :admin}matches maps that havename,age, androleequal to:admin. It bindsnameandageand formats the admin message.%{name: name, age: age} when age >= 18matches any map withnameandagewhere the guard confirms adulthood. This is a reminder of guards, now used insidecase.%{name: name, age: age}(no guard) catches the remaining valid user maps and labels them as minors._is the catch‑all for anything that doesn’t fit the expected shape. Order matters: more specific patterns go first.
Why this design? You keep logic declarative: match the shape of the input (a map with specific keys) and refine with guards only where needed.
Map Subset Matching and Why Ordering is Crucial
- Map patterns match subsets: a pattern like
%{name: name, age: age}will match any map that has at least those keys, even if it has extra keys (email,id, etc.). This also matches structs that define those fields (see below). - Because subset patterns can overlap, put more specific clauses first. For example, a struct clause or a clause that matches a specific
roleshould appear before a broader “hasnameandage” clause, otherwise the broader clause will grab the input and the specific one will never run.
Example of overlap and ordering:
If you switch the two clauses above, the second one will never run because the map subset clause will match both maps and structs.
What happens:
"Alice"matches the first clause (role: :admin) ->"Admin Alice is 30 years old"."Bob"matches the second clause (hasnameandage; guardage >= 18) ->"Adult user Bob"."Charlie"matches the third clause (hasnameandage; no guard) ->"Minor user Charlie is 15 years old".
This mirrors real systems where you branch by user role and age using clear, pattern-driven logic.
