Tuples

A tuple in Elixir is a group of a fixed number of values, written between braces. Where a list grows and shrinks, a tuple keeps its size, and that constant size is the point: the position of an item is part of what the value means. The smallest tuples carry the answers of functions, such as {:ok, value} and {:error, reason}, which a later lesson builds on.

A tuple is a fixed group

Braces hold the items, and a tuple with one item is written with a trailing comma so that it is not confused with the item itself. The items may have different types, and tuple_size/1 answers how many there are:

literal.exs

point = {3, 4} person = {"Ada", 36, :engineer} IO.inspect(point) IO.inspect(person) IO.puts(tuple_size(point)) IO.puts(tuple_size(person)) IO.inspect({:ok})

elixir literal.exs

{3, 4}
{"Ada", 36, :engineer}
2
3
{:ok}

The size is printed with the tuple because the inspect protocol shows the shape of the value. A tuple is stored as one block in memory with the size in its header, so tuple_size/1 is one step, while the length of a list walks its cells.

elem, put_elem and tuple_size

elem/2 reads one position, counted from zero, and put_elem/3 returns a new tuple with one item replaced. The original stays as it was, because the copy is a new block of the same size:

copy.exs

point = {3, 4} moved = put_elem(point, 0, 0) IO.inspect(point) IO.inspect(moved) IO.puts(tuple_size(moved)) IO.inspect(put_elem(point, 1, 9))

elixir copy.exs

{3, 4}
{0, 4}
2
{3, 9}

The copy is cheap because a tuple is small, and it is the reason a tuple is not the store for data that changes often. A value that moves from one position to another is data with a shape, and the shape is what the code reads.

Matching a tuple

The brace pattern binds the items by position, and a pattern that names fewer items than the tuple holds does not fit. A function that answers with two possible shapes is the usual partner of the brace pattern:

pattern.exs

{:ok, value} = {:ok, 42} IO.inspect(value) {a, b, c} = {1, 2, 3} IO.inspect({c, b, a}) defmodule Div do def safe(a, b) when b != 0, do: {:ok, a / b} def safe(_a, 0), do: {:error, :division_by_zero} end IO.inspect(Div.safe(10, 4)) IO.inspect(Div.safe(1, 0))

elixir pattern.exs

42
{3, 2, 1}
{:ok, 2.5}
{:error, :division_by_zero}

The first match takes the tuple apart; the second reorders it into a new one. The module returns a tuple whose first item says which shape it is, and the caller decides what to do with it. That convention is case against {:ok, value} and {:error, reason}, and case is where it reads best.

When a tuple is the right shape

A tuple says that the number of items and their meaning are known: a point has two coordinates, a version has three numbers, a result has a tag and a value. A map says that the keys are data, and a list says that the number is not known. Reaching for a tuple for a record that gains fields later is the mistake the next section shows in another form: every pattern that names the items breaks when the shape changes.

The mistake: an index past the end

elem/2 trusts the index it is given, and a tuple of two has no position 2. The call raises an ArgumentError that names the operator and the tuple:

mistake.exs

pair = {1, 2} IO.puts(elem(pair, 2))

elixir mistake.exs

** (ArgumentError) errors were found at the given arguments:

  * 1st argument: out of range

    :erlang.element(3, {1, 2})
    mistake.exs:1: (file)

The error comes from the Erlang function behind elem/2, and the index in the message is one higher than the one in the call. The fix is a pattern that names the positions the program really has, or Tuple.to_list/1 when the index is a value the program computes. A tuple is read by shape, and a shape that does not fit is a bug in the code rather than a value to test at run time.

The programs on this page were run with Elixir 1.19.7 on Erlang/OTP 27 (erts 15.2.7.14), on Linux x86_64 in a Docker container.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Why is tuple_size/1 one step, whatever the tuple?

    Answer

    The size is stored in the tuple header

    A tuple is one block with its size in the header, so the count is read rather than walked.

  2. When is a tuple the right store for data?

    Answer

    When the number of items and their meaning are fixed

    A tuple encodes a fixed shape; a map is the store whose keys can change.

  3. What happens when a brace pattern names fewer items than the tuple holds?

    Answer

    The pattern does not match

    The brace pattern checks the size as well as the positions, so a shape that differs does not match.

  4. What does this program print? IO.inspect(elem({:a, :b}, 1))

    Answer

    :b

    elem/2 counts from zero, so index 1 is the second item.

  5. What does this program print? IO.inspect(put_elem({1, 2}, 0, 9))

    Answer

    {9, 2}

    put_elem/3 replaces the item at the index and returns a new tuple of the same size.

  6. What does this program print? {a, b} = {1, 2} IO.puts(a + b)

    Answer

    3

    The pattern binds a to 1 and b to 2, and the sum is 3.

  7. What does this program print? IO.inspect(tuple_size({:a}))

    Answer

    1

    A one-item tuple is still a tuple, and its size is 1.

  8. What does this program print? IO.inspect(elem({1, 2, 3}, 2))

    Answer

    3

    Index 2 is the third item of the tuple.

  9. What does this program do? {a, b} = {1, 2, 3} IO.puts(a + b)

    Answer

    A MatchError, because the pattern has two names and the tuple has three items

    The pattern names a shape of two items and the value has three, so the match fails.

  10. What does this program do? pair = {1, 2} IO.puts(elem(pair, 2))

    Answer

    An ArgumentError, because the index is out of range

    elem/2 raises when the index is not a position of the tuple.

Article author: Arthur Isaev