F3.02 · part 1 of 3
The match operator
The single = does two jobs at once: it asserts that the value on the
right matches the pattern on the left, and it binds any unbound names in that pattern. To compare against a
value you already hold rather than rebind it, you pin the name with ^.
The portal keeps the signed-in learner's id in user_id. When a new
request arrives carrying a user id, the question is whether it belongs to the same learner. A plain match
would quietly overwrite the original; a pinned match asserts they are equal — and fails loudly if not.
Bind or pin
Start with user_id already bound to the signed-in learner. Choose whether the
next match is plain or pinned, and whether the incoming id is the same or different. Watch what the match
does.
Match · plain or pinned
Plain = always succeeds by rebinding; ^
turns the name into an assertion. Reach for the pin whenever a value must equal one you already trust —
a session's learner, an expected token.
Why it matters
Because a bare name in a pattern always matches and binds, it can hide bugs: write
user_id = request.user_id expecting a check, and you have instead silently
replaced the learner you were tracking. The pin makes the intent explicit and lets a mismatch surface as a
MatchError at the exact line, rather than as a wrong result three functions
later.
Plain match
A name on the left binds — it never compares, so it cannot fail.
Pinned match
^user_id uses the current value as a literal to match against.
Next: destructuring portal data — using a match to pull fields out of the claims, params, and progress records the portal handles.
References
Primary sources for this lesson, and where it connects in the course.
Sources
- Pattern matching — Elixir documentation —
=as the match operator, and the pin. - case, cond, and if — Elixir documentation — matching in control flow.