F3.02 · part 2 of 3
Destructuring portal data
The same match operator pulls values out of compound data. Put the shape you expect on the left, with names where the interesting parts are, and those names bind to the matching pieces — tuples by position, maps and structs by key, lists by head and tail.
The portal moves a handful of shapes around: the claims decoded from a magic-link token, the params from a sign-in request, a progress record, and the list of lessons a learner has finished. Each is taken apart with one pattern.
Take it apart
Select a piece of portal data to see the pattern that destructures it and the names it binds.
Destructuring · select a shape
One line replaces a fistful of accessor calls. The pattern reads like the data it expects, so the shape of the input is visible at the point you use it.
What binds, what is ignored
A map pattern matches when the listed keys are present; any other keys are ignored, which
is what lets you read only the email from a claims map full of fields. A
struct pattern additionally asserts the struct's type. A list pattern
[head | tail] splits off the first element. To match a position without binding
it, use the underscore _.
- tuple
{:ok, value}— fixed size, matched by position.- map
%{key: var}— listed keys must exist; extras are ignored.- struct
%Progress{field: var}— like a map, and the type is asserted.- list
[head | tail]— first element and the remaining list.
F2 · algebraic data types
Products hold fields together; a value is some nesting of tuples, maps, and lists.
F3 · destructuring
A pattern mirrors that nesting and binds the parts you name, in one match.
Next: branching with case, with & guards — using these patterns to drive the portal's sign-in flow.
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.