Reading — step 1 of 5
Learn
~1 min readTuples and Records
Tuples group a fixed number of values. Written with {}:
Point = {3, 4},
{X, Y} = Point, % pattern match — X=3, Y=4
Person = {person, "Ada", 36}, % tagged tuple — convention
Tagged tuples are an Erlang convention: the first element is an atom describing the tuple's purpose. The Erlang ecosystem uses this everywhere:
{ok, Value} % success
{error, Reason} % failure
Functions return tagged tuples instead of throwing:
case file:read_file("data.txt") of
{ok, Contents} -> use_data(Contents);
{error, Reason} -> log_error(Reason)
end.
case is Erlang's pattern-match expression. It's like a switch that destructures.
case X of
0 -> zero;
N when N > 0 -> positive;
_ -> negative
end
Clauses end with ;, the whole case ends with end.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…