Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 36 ยท Data Structures

Tuples and Records

Use Erlang tuples for fixed-size groups, tagged tuples for results, and records for named fields with defaults, updates, pattern matching and header files.

A tuple groups a fixed number of terms into one value. Where a list is for sequences of any length, a tuple is for a small number of items whose positions have meaning: a coordinate {X, Y}, a result {ok, Value}, a message {deposit, Amount}. Records add field names on top of tuples, which helps when a tuple would have many positions.

Tuples

ERLANG
1> P = {3, 4}.
{3,4}
2> element(1, P).
3
3> tuple_size({a, b, c}).
3
4> setelement(2, {a, b, c}, x).
{a,x,c}
5> {X, Y} = P.
{3,4}
6> {Name, {Street, City}} = {"Ada", {"Main St", "London"}}.
  • element(N, Tuple) reads position N (1-based, constant time).
  • setelement(N, Tuple, Value) returns a new tuple with that position changed; the original is untouched.
  • tuple_size/1 gives the size.
  • Convert with tuple_to_list/1 and list_to_tuple/1.

Tuples are stored in contiguous memory, so reading an element is fast, but updating copies the whole tuple. For big or frequently changed data, prefer maps.

Tagged tuples

The first element is often an atom that says what the rest means. This tagged tuple convention is everywhere in Erlang:

ERLANG
{ok, 42}
{error, enoent}
{circle, 5}
{rectangle, 3, 4}
{user, "Ada", 36}

Patterns can take them apart and choose a branch by tag, as in the area function from pattern matching. The same tuple can act as a "return value with a status" or a message in a mailbox.

Why records?

A tuple like {person, "Ada", 36, "London", engineer} is easy to get wrong: which position is the age? Add a field in the middle and you have to rewrite every pattern. A record names the positions at compile time.

ERLANG
-module(people).
-export([new/2, birthday/1, show/1]).

-record(person, {name, age = 0, city = "unknown"}).

new(Name, Age) ->
    #person{name = Name, age = Age}.

birthday(P) ->
    P#person{age = P#person.age + 1}.

show(#person{name = N, age = A, city = C}) ->
    io:format("~s, ~p, ~s~n", [N, A, C]).

The -record attribute defines the name and fields, optionally with defaults. After that:

  • #person{name = "Ada", age = 36} creates a record; omitted fields get their default or undefined.
  • P#person.age reads the field age.
  • P#person{age = 37} creates a copy of P with age changed.
  • #person{name = N} can be used in patterns and guards.
  • #person.age (without a record variable) gives the field's position number.
ERLANG
1> rr(people).
[person]
2> P = people:new("Ada", 36).
#person{name = "Ada",age = 36,city = "unknown"}
3> P2 = people:birthday(P).
#person{name = "Ada",age = 37,city = "unknown"}
4> P2#person.age.
37
5> people:show(P2).
Ada, 37, unknown

rr(Module) makes the shell aware of the records in a module so it can print them nicely; use rd/2 to define one on the spot.

Records are tuples in disguise

The compiler turns #person{name = "Ada", age = 36, city = "London"} into the tuple {person, "Ada", 36, "London"}: the first element is the record name. This is why records are cheap, and why you must not mix them up with real tuples.

ERLANG
1> {person, N, A, C} = #person{name = "Ada", age = 36, city = "London"}.

Because the compiler expands records at compile time, the definition must be visible wherever a record is used. Records are not dynamic: you cannot look up a field by a runtime name.

Records in header files

When several modules share a record, put the definition in an .hrl file under include/ and include it:

ERLANG
%% include/person.hrl
-record(person, {name, age = 0, city = "unknown"}).
ERLANG
-module(reports).
-include("person.hrl").

Use -include_lib("my_app/include/person.hrl") in rebar3 projects to find headers through the application name. A changed record means every module using it must be recompiled; after hot upgrades a stale module sees the old layout, which is a reason many modern codebases prefer maps.

Records or maps?

Need Choice
Fixed set of fields, speed, compile-time checks Record
Dynamic keys, easy printing, JSON-like data Map
Two or three positions, short-lived Tuple

Stand-ins in JavaScript

Tuples map to arrays and records to objects with defaults. These samples are not Erlang.

JS Stand-in: tuples are immutable, setelement copies (JavaScript, not Erlang)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Stand-in: records with defaults and update syntax (JavaScript, not Erlang)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does setelement(2, {a,b,c}, x) return?

    setelement returns a new tuple with position 2 replaced; positions start at 1.
  2. 2. How is a record stored at runtime?

    #person{...} compiles into {person, Field1, Field2, ...}.
  3. 3. How do you create a copy of record P with a new age?

    The update syntax Rec#name{field = Value} copies the record and changes the given fields.
  4. 4. Where should a record used by several modules be defined?

    Put the -record attribute in a header and -include it where needed.

Summary

  • Tuples are fixed-size, 1-indexed groups; updating copies them.
  • Tagged tuples such as {ok, V} and {error, R} carry meaning through their first atom.
  • Records name tuple positions at compile time: -record, #r{}, R#r.field, R#r{field = V}.
  • Share records through .hrl header files; use rr/1 in the shell to see them.
  • Prefer maps when keys are dynamic or data changes often.

Next: Maps