Tuples

A tuple is a fixed-size group of values in one term. The first element usually names the kind of value, the rest carry the data, and the whole thing moves as one message or one result. Erlang uses tuples where other languages use a small object or a return code pair.

Pairs and more

Curly braces build a tuple, and the items may have different types. The size is fixed at creation: the tuple never grows or shrinks in place, and an update builds a new one. A tuple of two items is a pair, and the empty tuple is a value of its own:

erl

1> {ok, 42}. {ok,42} 2> {point, 1, 2}. {point,1,2} 3> {}. {} 4> element(1, {point, 1, 2}). point

The first item is a tag by convention, not by rule: the runtime does not care, but a reader and a pattern do. The tag makes a tuple recognisable by its first element, which is why {ok, Value} and {error, Reason} are so common.

Access by index

element/2 reads a position counting from one, and tuple_size/1 counts the items. size/1 answers the same for a tuple or a binary but refuses a list, and setelement/3 returns a new tuple with one position replaced:

erl

1> T = {ok, 42}. {ok,42} 2> element(2, T). 42 3> tuple_size(T). 2 4> size(T). 2 5> setelement(2, T, 7). {ok,7} 6> T. {ok,42}

The last two lines are the rule in action: setelement/3 returns a new tuple and leaves T at its old value. Index access is fine for a two-item result; a pattern reads better as soon as the shape matters.

Match inside

Tuples match deeply: a pattern with a tuple matches only a tuple of the same size, and the values inside bind in the same move. The position takes the value, and the tag must match exactly:

erl

1> {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 failed match is the useful part: a caller that expects an error tuple cannot mistake a success for one, because the tag does not fit. This is how a function unpacks its argument without element/2 and without a case.

The ok and error shape

A function that can fail in an expected way returns a tuple instead of raising: {ok, Value} for success and {error, Reason} for failure. The caller has to match the tuple to get the value, so the failure case is visible in the code. This module returns the two shapes and prints each through one case:

divide.erl

-module(divide). -export([main/0, divide/2]). divide(_A, 0) -> {error, div_by_zero}; divide(A, B) -> {ok, A / B}. print(Result) -> case Result of {ok, Value} -> io:format("ok: ~p~n", [Value]); {error, Reason} -> io:format("error: ~p~n", [Reason]) end. main() -> print(divide(5, 2)), print(divide(1, 0)).

erlc divide.erl

erl -noshell -eval 'divide:main(), halt().'

ok: 2.5 error: div_by_zero

divide/2 has no exception for the zero: the zero is an expected answer, so it is a value. An exception is for a bug the caller did not plan for, and the exceptions lesson draws that line. The GenServer lesson shows how a server answers a call with the same shape.

A tuple never changes

A tuple can carry more than two fields, and a function that moves one field returns a new tuple of the same shape. This module tags a point, moves it, and prints the result; the pattern in the head reads the fields by position:

point.erl

-module(point). -export([main/0, point/2, move/3]). point(X, Y) -> {point, X, Y}. move({point, X, Y}, DX, DY) -> {point, X + DX, Y + DY}. main() -> P = point(1, 2), io:format("~p~n", [move(P, 3, 4)]).

erlc point.erl

erl -noshell -eval 'point:main(), halt().'

{point,4,6}

Position-based fields are hard to read once a tuple has more than three items. That is the point where a record gives the same tuple names for the fields, and a map gives them names that a running program can add or remove. A tuple of a different arity is a different value, which this last module uses to answer both a result and a shape:

extent.erl

-module(extent). -export([main/0, extent/1]). extent([]) -> {error, empty}; extent(List) -> {ok, lists:min(List), lists:max(List)}. main() -> io:format("~p~n", [extent([3, 1, 4])]), io:format("~p~n", [extent([])]).

erlc extent.erl

erl -noshell -eval 'extent:main(), halt().'

{ok,1,4} {error,empty}

Questions

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

  1. How do you write a tuple?

    Answer

    {ok, 42}

    Curly braces build a tuple, a fixed-size group of values.

  2. Can a tuple grow after it is created?

    Answer

    No, its size is fixed

    A tuple keeps the size it was built with; changing it means building a new tuple.

  3. From which number does element/2 count positions?

    Answer

    One

    Tuple positions start at one, so element(1, {ok, 42}) is ok.

  4. What does setelement(2, {ok, 42}, 7) return?

    Answer

    {ok,7} and the old tuple is unchanged

    The function returns a new tuple with the second position replaced; the original term never changes.

  5. What happens for {error, _} = {ok, 42}.?

    Answer

    A badmatch exception is raised

    The tuple tags differ, so the match fails with no match of right hand side value.

  6. What does this module print? -module(q4). -export([main/0]). move({point, X, Y}, DX) -> {point, X + DX, Y}. main() -> io:format("~p~n", [move({point, 1, 2}, 3)]).

    Answer

    {point,4,2}

    The pattern binds X to 1 and Y to 2, and the body returns {point,1+3,2}.

  7. Why does Erlang prefer the ok tuple to exceptions for expected failures?

    Answer

    The caller must handle the answer explicitly

    A tuple is an ordinary value, so the caller matches it and cannot forget the failure case.

  8. What does this module print? -module(q1). -export([main/0]). main() -> io:format("~p~n", [element(1, {point, 3, 4})]).

    Answer

    point

    Positions start at one, so element 1 is the tag point.

  9. What does this module print? -module(q2). -export([main/0, divide/2]). divide(_A, 0) -> {error, div_by_zero}; divide(A, B) -> {ok, A / B}. main() -> io:format("~p~n", [divide(1, 0)]).

    Answer

    {error,div_by_zero}

    The first clause matches a zero denominator and returns the error tuple.

  10. What does this module print? -module(q3). -export([main/0, extent/1]). extent([]) -> {error, empty}; extent(List) -> {ok, lists:min(List), lists:max(List)}. main() -> io:format("~p~n", [extent([3, 1, 4])]).

    Answer

    {ok,1,4}

    The smallest value is 1 and the largest is 4, and both fit in one three-item tuple.

The examples on this page were compiled and run with Erlang/OTP 27 (erts-15.2.7.14) on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Автор статьи: Arthur Isaev