ELIXIR / CHAPTER 01

Immutable values and pattern matching

Intermediate

Use matching and rebinding without confusing them with mutation.

By the end of this chapter

  • Extract tuple fields with patterns
  • Distinguish rebinding from changing a value
  • Use the pin operator for an existing value

The idea

Enter with basic functions and collections understood. In Elixir, = is a match operator: it succeeds when the value on the right fits the pattern on the left. A variable in a pattern can receive a binding, and tuple patterns can extract several related pieces at once. A mismatched shape raises an error instead of silently inventing missing data.

Values are immutable. Rebinding a variable name makes that name refer to another value; it does not alter the previous value or other bindings referring to it. The pin operator ^ asks a pattern to match an existing variable’s value instead of rebinding that variable. This distinction matters in parsing, function clauses, and message handling, where a familiar name alone may not express an equality check.

Elixir example
{:ok, count} = {:ok, 5}
old = count
count = count + 2
IO.inspect({old, count})
Result
{5, 7}

The tuple match binds count to five. Rebinding count later leaves the value associated with old unchanged.

Try it yourself

Match a tuple {:point, 3, 4} and compute the sum of its two coordinates.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

With x already bound to 4, which pattern requires the next value to equal 4?