Elixir Tuples
A tuple is a fixed-size collection that groups a small set of values together. Tuples often pair a status atom like :ok with a result value.
A tuple groups values together
Curly braces create a tuple. This one pairs a status atom with a number.
result = {:ok, 42}
IO.inspect(result)elem reads one value by index
The elem function reads a value at a position. Index 0 is the first value and index 1 is the second.
pair = {:error, 404}
IO.inspect(elem(pair, 0))
IO.inspect(elem(pair, 1))put_elem returns a new tuple
The put_elem function replaces one value in a copy. The original tuple stays unchanged.
data = {10, 20, 30}
IO.puts(tuple_size(data))
updated = put_elem(data, 1, 99)
IO.inspect(updated)
IO.inspect(data)Example
response = {:ok, "saved", 201}
IO.inspect(elem(response, 0))
IO.inspect(elem(response, 2))
IO.puts(tuple_size(response))
changed = put_elem(response, 2, 200)
IO.inspect(changed)Key points
- Tuple literal: Curly braces hold the values, such as {:ok, 42}.
- Fixed size: A tuple keeps the number of values it was created with.
- elem: Use elem(tuple, index) to read one value, and indexes start at 0.
- tuple_size: Use tuple_size(tuple) to count the values in a tuple.
- put_elem: Use put_elem(tuple, index, value) to build a new tuple with one value replaced.
- Result tuples: The pair {:ok, value} reports success and {:error, reason} reports failure.
In this example, the tuple holds a status, a message, and a code. The elem calls read the status at index 0 and the code at index 2, and tuple_size reports 3 values. The put_elem call then builds a new tuple with the code replaced by 200.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What is the value of elem({:ok, 5}, 1)?