F3.02 · part 3 of 3
Branching with case, with & guards
Matching earns its keep when it chooses what runs next. Function heads match arguments to pick
a clause; case matches a value against several patterns; with
chains matches and stops at the first that fails; and guards add conditions with when.
The portal's sign-in is a sequence of steps that can each fail: verify the magic-link token,
load the learner, start a session. That is exactly the shape with was made for —
a happy path of successful matches, and one place to handle whatever went wrong.
The sign-in flow
The with below runs three steps, each returning {:ok, _}
or {:error, _}. Toggle any step to fail and watch where the pipeline
short-circuits — control jumps straight to the else, carrying the error.
with · toggle a step to fail
One happy path, read top to bottom, and a single else for every
failure. No nested conditionals, and no way to forget a branch — an unmatched error falls through
to else.
The four forms
The flow above leans on with, but the same matching drives the other branching
forms. The portal uses each: function heads to handle progress events by tag, case
to inspect a single result, and guards to add conditions such as an unexpired token.
# function heads: one clause per event shape def handle({:lesson_completed, user_id, lesson_id}), do: Progress.mark(user_id, lesson_id) def handle({:lesson_started, _user_id, _lesson_id}), do: :ok # case: branch on one value case Portal.Auth.verify(token) do {:ok, claims} -> sign_in(claims) {:error, reason} -> deny(reason) end # guard: a condition on the match def valid?(%{exp: exp}) when exp > now(), do: true
F1 · equations by cases
A function defined piecewise: a different rule for each shape of input.
F3 · matching dispatch
Function heads, case, and with choose a branch by matching the value.
That completes F3.02. The portal can now read a magic-link result and act on it. Next module: F3.03 — Functions, modules & the pipe. Return to the chapter overview for the full path.
References
Primary sources for this lesson, and where it connects in the course.
Sources
- Pattern matching — Elixir documentation —
=as the match operator. - case, cond, and if — Elixir documentation — matching in control flow.