Elixir basics · Lesson 05 (open contents)
01 · Let the code speak02 · Meet six kinds of values03 · Put values together04 · Build a new list05 · Make the shapes match06 · Choose with case07 · Parse a number safely08 · Unpack &1 and the pipe09 · Put code in a project10 · Ask precise true-or-false questions11 · Read and update nested data12 · Count visible text and bytes13 · Let function clauses choose14 · Solve a list twice15 · Choose the smallest clear control form16 · Give domain data a shape17 · Put one tested module in Mix18 · Make success and failure predictable19 · Read and write one real file20 · Take only the data you need21 · Give different data one shared action22 · Write a callback contract23 · Write down the data contract24 · Test behavior and boundaries25 · Turn a project into a command26 · Write the project promise27 · Parse one real line28 · Keep the public API small29 · Make the promise executable30 · Package the edge and leave clues31 · Prove the project is done
ELIXIR · SCRATCH · LESSON 0525 minutes

Make the shapes match

Treat `=` as a match and unpack tuples, lists, and maps.

01 · Start with the whole example

Unpack three kinds of collections

Read the shape on the left first. Then find each matching value on the right.

Elixir
# Save the tag we expect
expected_tag = :ok

# ^ checks the old expected_tag value; _ ignores the third value
{^expected_tag, score, _} = {:ok, 92, :midterm}

# Split the first item from the rest of a list
[first | rest] = ["peach", "plum", "apricot"]

# A map pattern names only the key we need
%{name: name} = %{name: "Robin", age: 12}

{score, first, rest, name}
Check the result first
  • score becomes 92.
  • first becomes "peach", and rest becomes ["plum", "apricot"].
  • name becomes "Robin".
02 · Take the code apart

Read from the first line down

  1. ^expected_tag does not bind the name again. It requires the tuple's first item to equal the existing :ok; _ ignores the third value.
  2. [first | rest] matches only a non-empty list. The bar separates the first item from the remaining list.
  3. A map pattern can name only the keys it needs. The extra age key does not stop this match.
03 · Meet the new symbols

Symbols are not secret signs

=

Match the two sides. New names on the left bind to the matching values.

_

The value in this position does not need to be saved.

[head | tail]

Split a non-empty list into its first item and the remaining items.

^name

Check this position against the value already stored in name. Read it as pin name.

04 · Ideas inside the code

Match each name to its meaning

01

pattern

A shape on the left that checks and unpacks the data on the right.

02

destructuring

Taking several values out of a collection at once.

03

match failure

When the shapes or fixed values do not line up, Elixir raises a MatchError.

04

pin operator

^name uses the value already bound to name instead of binding a new value in that position.

05 · Make the idea clear

Why these forms are useful

In Elixir, = does more than assign a value. It checks whether the shapes on both sides can match.

The left side is like a form with empty spaces. The data on the right fills them. If a position, label, or key does not fit, the match fails.

This is often used to unpack data. Write only the parts you need. An underscore _ can take the rest.

A plain name in a pattern receives a value. To check against a value that name already holds, add the pin operator ^. ^expected_tag means “this position must equal the old value of expected_tag.”

DESIGN DECISION

Why this shape?

Why is = more than assignment here?

Choice

A pattern checks a shape and extracts its data in one move. The same idea works at function boundaries, in case, and in receive.

Cost and boundary

The rules differ across a new match: Elixir rebinds a plain name and needs ^name to check the old value; an Erlang variable becomes a check after its first binding.

A FAMILIAR POINT OF VIEW

Coming from Java, Python, or JavaScript

Java

Familiar starting point
Assign a local variable, then inspect an object with accessors or instanceof.
What BEAM changes
A pattern checks and unpacks tuples, lists, or maps directly.
False friend
This is not method overloading, and it does not mutate the value.

Python

Familiar starting point
Unpacking and match/case offer a familiar starting point.
What BEAM changes
Data is not changed in place, and patterns are routine tools for function clauses and message protocols.
False friend
Elixir can rebind a name without mutating its old value; a bound Erlang variable checks the next match.

JavaScript

Familiar starting point
Array and object destructuring mainly extract values.
What BEAM changes
BEAM patterns can also require fixed tags; a mismatch selects another clause or fails.
False friend
JavaScript destructuring defaults follow different rules.
06 · Change it yourself

Close the answer and try

Bind the expected tag, then check it while unpacking the city and temperature from {:weather, "York", 28}.

Practice starting point
# Accept only a weather message
expected_tag = :weather

# Pin the old tag and name the other two positions
{^____, ____, ____} = {:weather, "York", 28}

# Return the city and temperature
{city, temperature}

Target result: The result should be {"York", 28}.

Stuck? Read one hint

Put ^expected_tag first, followed by city and temperature.

After you run it, see one answer
One answer
# Save the tag we plan to check
expected_tag = :weather

# ^expected_tag must match; two new names receive the data
{^expected_tag, city, temperature} = {:weather, "York", 28}

# Look at the values we unpacked
{city, temperature}
Think about it: Will `{:ok, value} = {:error, 3}` succeed?

No. The left side requires :ok, but the right side begins with :error, so Elixir raises a MatchError.

Take with you

Remember these three lines

  1. 1

    = checks a shape. It does not only put a value into a name.

  2. 2

    Fixed values check the data. New names receive it.

  3. 3

    Use ^name to check an old value and _ for a value you do not need.

Lesson completeRun the code once, then mark this lesson as done.