Tuples
| Pairs and more | |
| Access by index | |
| Match inside | |
| The ok and error shape |
Pairs and more
Curly braces build a tuple, a fixed-size group of values. Tuples hold related items of different types, like a status with its payload.
The size is fixed at creation, so a tuple never grows or shrinks in place.
{ok, 42}.
{ok,42}
2> {point, 1, 2}.
{point,1,2}
3> {}.
{}
Access by index
The element function reads a position starting from one, and tuple_size counts the items. The size function answers the same for tuples and lists.
Index access is fine for ad-hoc work, but pattern matching, the next section, reads better.
T = {ok, 42}.
2> element(2, T).
42
3> tuple_size(T).
2
Match inside
Tuples match deeply: a pattern with a tuple inside matches only tuples of the same shape. The values inside bind to names in the same move.
This is how Erlang unpacks results: match the tuple, and the parts arrive as variables.
{ok, Value} = {ok, 42}.
{ok,42}
2> Value.
42
3> {error, _} = {ok, 42}.
** exception error: no match of right hand side value {ok,42}
The ok and error shape
Erlang functions answer expected failures with tuples instead of exceptions. Callers match {ok, Value} for success and {error, Reason} for failure, and the compiler checks nothing: the pattern does.
The convention is so common that it has a name: the ok tuple. Lesson 34 shows how a GenServer answers calls with the same shape.
divide(_, 0) -> {error, div_by_zero};
divide(A, B) -> {ok, A / B}.
Next: Maps
Article author: Arthur Isaev