Everything is a term
Every piece of data in Erlang, from the number 42 to a message travelling between machines, is a term. There are only a handful of kinds of term, and they combine freely: a tuple can contain lists, which contain maps, which contain more tuples. There are no classes, no objects and no null pointers.
Terms have two properties that shape the whole language. They are immutable: once created, a term never changes, and "modifying" a list really means building a new one. And variables are single assignment: once a variable is bound to a value, it keeps that value for the rest of its scope. If that sounds limiting, consider what it buys. Two processes can never see a term change underneath them, so there is nothing to lock. A function that receives a term can never surprise its caller by altering it. And the = sign is freed from meaning "assign", so it can mean something more useful: match.
This lesson covers the kinds of term, how to compare them, and pattern matching, the tool you will use on almost every line of Erlang you write.
The kinds of term
| Term | Examples | Notes |
|---|---|---|
| integer | 42, -7, 1_000_000, 16#FF, 2#1010, $A | unlimited size; Base#Digits for other bases; $A is the character code 65 |
| float | 3.14, 1.0e-9 | 64-bit IEEE 754 |
| atom | ok, error, true, 'Hello World' | a named constant; lowercase, or any text in single quotes |
| tuple | {point, 3, 4} | fixed number of elements |
| list | [1, two, "three"], [] | linked list of any terms |
| string | "text" | shorthand for a list of character codes |
| binary | <<"text">>, <<1, 2, 255>> | a compact sequence of bytes |
| map | #{name => "Kwame"} | key-value pairs, any term as key |
| fun | fun(X) -> X * 2 end | a function as a value |
| pid, reference, port | <0.89.0> | identify processes, unique tokens and external resources |
Atoms are everywhere in Erlang: ok, error, undefined, module names like lists, and the booleans, which are simply the atoms true and false. Variables are the opposite: they start with an uppercase letter or an underscore (Count, _Ignored). That one rule, lowercase for constants and uppercase for variables, makes Erlang code easy to scan.
A tuple whose first element is an atom, such as {point, 3, 4} or {error, timeout}, is called a tagged tuple, and it is Erlang's basic way to label data. Functions that can fail conventionally return {ok, Value} or {error, Reason}.
Operators hold a few surprises:
#!/usr/bin/env escript
main(_) ->
io:format("~p~n", [[16#FF, 2#1010, $A, 1_000_000]]),
io:format("~p ~p ~p~n", [7 / 2, 7 div 2, 7 rem 2]),
io:format("~p~n", [2 * 1.5]),
io:format("~p~n", [math:pow(2, 0.5)]),
io:format("~p ~p~n", [1 == 1.0, 1 =:= 1.0]),
io:format("~p ~p~n", [3 =< 3, 2 /= 2.0]),
io:format("~p~n", [[is_atom(ok), is_atom(true), is_atom('Hello World')]]),
io:format("~p~n", [{point, 3, 4}]),
io:format("~p~n", [#{name => "Kwame", langs => [erlang, elixir]}]),
io:format("~p~n", [tuple_size({a, b, c})]),
io:format("~p~n", [length([1, two, "three", {4}])]),
io:format("~p~n", [true andalso (1 < 2)]),
io:format("~p~n", [lists:sort([{1}, 7, "b", ok, [x], 2.5, #{}, <<"z">>])]).It prints:
[255,10,65,1000000]
3.5 3 1
3.0
1.4142135623730951
true false
true false
[true,true,true]
{point,3,4}
#{name => "Kwame",langs => [erlang,elixir]}
3
4
true
[2.5,7,ok,{1},#{},"b",[x],<<"z">>]/always produces a float;divandremare integer division and remainder.==compares numbers by value, so1 == 1.0is true;=:=("exactly equal") also requires the same type. Their negations are/=and=/=. Most Erlang code uses=:=and=/=unless it deliberately wants numeric comparison.- "Less than or equal" is written
=<, not<=(which means something else, in binary comprehensions). This is the single most common typo for newcomers. andalsoandorelseare the short-circuit boolean operators: the right side is only evaluated if needed. Erlang also hasandandor, which always evaluate both sides; preferandalso/orelse.- Any two terms can be compared, even of different types, because Erlang defines a total order: numbers < atoms < references < funs < ports < pids < tuples < maps < lists < binaries. That is why
lists:sort/1could sort a list of mixed types above. It sounds odd, but it means any term can be a key in a sorted structure.
The map printed its keys in a different order from the one we wrote. Maps have no defined order when printed or iterated; never depend on it.
Single assignment and pattern matching
Definition— Pattern match
Pattern = Expression evaluates the expression and matches the result against the pattern. Unbound variables in the pattern become bound to the corresponding parts; already-bound variables must equal the corresponding parts. If the match fails, the process raises a badmatch error.
#!/usr/bin/env escript
main(_) ->
{Status, Count} = {ok, 3},
io:format("Status=~p Count=~p~n", [Status, Count]),
[First, Second | Rest] = ["Accra", "Hanoi", "Lima", "Oslo"],
io:format("First=~s Second=~s Rest=~p~n", [First, Second, Rest]),
#{name := Name} = #{name => "Ifeoma", role => admin, active => true},
io:format("Name=~s~n", [Name]),
{date, {Year, _, _}} = {date, {2026, 11, 19}},
io:format("Year=~p~n", [Year]),
{Same, Same} = {7, 7},
io:format("Same=~p~n", [Same]),
"Bearer " ++ Token = "Bearer abc123",
io:format("Token=~s~n", [Token]),
<<"GET ", Path/binary>> = <<"GET /index.html">>,
io:format("Path=~s~n", [Path]),
Result = try
{ok, Phone} = find_phone("Zeynep"),
Phone
catch
error:{badmatch, Bad} -> {no_match, Bad}
end,
io:format("~p~n", [Result]).
find_phone("Ana") -> {ok, "+351 21 000 0000"};
find_phone(_) -> {error, not_found}.It prints:
Status=ok Count=3
First=Accra Second=Hanoi Rest=["Lima","Oslo"]
Name=Ifeoma
Year=2026
Same=7
Token=abc123
Path=/index.html
{no_match,{error,not_found}}Each line shows a different shape:
- Tuples match element by element and must have the same size.
- Lists split into head and tail with
[H | T];[A, B | Rest]takes two elements from the front. - Maps match with
:=, and only the keys you mention need to be present. (When building a map you write=>; when matching or updating an existing key,:=.) - Patterns nest:
{date, {Year, _, _}}reaches inside the inner tuple._matches anything and binds nothing. {Same, Same}uses one variable twice, so it matches only when both elements are equal."Bearer " ++ Tokenmatches a string with a known prefix, and<<"GET ", Path/binary>>does the same for a binary. You will see much more binary matching in Lists, tuples, maps and binaries.- When a match fails, the process raises the error
{badmatch, Value}. Here we catch it to show it; normally you would let it crash, as later lessons explain.
There is no way to reassign a variable, and you never need one. Instead of X = X + 1, you write X1 = X + 1, or more often, you pass the new value to a recursive call, as the next lesson shows.
case: choosing by shape
case Expression of Pattern1 -> Body1; Pattern2 -> Body2 end tries each pattern in order and evaluates the body of the first that matches. A pattern may be followed by a guard, when Condition, that must also hold. Like everything in Erlang, case is an expression and returns a value.
#!/usr/bin/env escript
main(_) ->
Results = [{ok, 12}, {error, not_found}, {ok, 30}, {error, timeout}],
lists:foreach(fun describe/1, Results),
Expected = "Zanele",
io:format("~s~n", [check({"Zanele", 92}, Expected)]),
io:format("~s~n", [check({"Thabo", 77}, Expected)]).
describe(Result) ->
Text = case Result of
{ok, N} when N > 20 -> io_lib:format("big success: ~p", [N]);
{ok, N} -> io_lib:format("success: ~p", [N]);
{error, timeout} -> "timed out, will retry";
{error, Reason} -> io_lib:format("failed: ~p", [Reason])
end,
io:format("~s~n", [Text]).
check(Score, Expected) ->
case Score of
{Expected, Points} -> io_lib:format("~s scored ~p", [Expected, Points]);
{Other, _} -> "unexpected student " ++ Other
end.It prints:
success: 12
failed: not_found
big success: 30
timed out, will retry
Zanele scored 92
unexpected student Thabodescribe/1 is the classic way to consume tagged tuples: the specific {error, timeout} comes before the general {error, Reason}, and the guard when N > 20 separates big successes from ordinary ones. io_lib:format/2 works like io:format/2 but returns the text instead of printing it.
check/2 shows something that differs from many languages with pattern matching. Expected is already bound when the case runs, so in the pattern {Expected, Points} it is not a new variable: it must equal the existing value. Erlang needs no special syntax for this (Elixir, for instance, uses a pin operator ^). New variables such as Points and Other are bound by the clause that matches. If no clause matches, case raises a case_clause error, which is usually what you want: an unexpected value is a bug.
A related habit: a variable bound inside one clause of a case is "unsafe" to use after the case unless every clause binds it. The compiler will tell you, and the fix is usually to make the case return the value you need.
Strings, binaries and Unicode
Erlang has two ways to hold text, and you will meet both every day.
A string in double quotes is just a list of integers, one per character (Unicode code point). It is convenient to build and match, but each character costs a list cell of 16 bytes on a 64-bit machine. A binary string, <<"text"/utf8>>, holds UTF-8 bytes compactly and is what modern code uses for anything large or long-lived: data from files and sockets, JSON, database rows. OTP 27 added two conveniences: the sigil ~"..." for a UTF-8 binary, and triple-quoted strings for multi-line text, which strip the indentation of the closing quotes.
#!/usr/bin/env escript
main(_) ->
List = "Zürich",
Bin = <<"Zürich"/utf8>>,
io:format("~p~n", [List]),
io:format("~w~n", [List]),
io:format("~p ~p~n", [length(List), byte_size(Bin)]),
io:format("~ts | ~ts~n", [List, Bin]),
io:format("~p~n", [string:length(Bin)]),
io:format("~ts~n", [string:uppercase(Bin)]),
io:format("~p~n", [string:split("red,green,blue", ",", all)]),
io:format("~p~n", [string:lexemes(<<" spaced out ">>, " ")]),
Anil = unicode:characters_to_binary("añil"),
io:format("~p versus ~tp~n", [Anil, Anil]),
io:format("~p~n", [~"a binary string"]),
Poem = """
Line one
indented line two
""",
io:format("~ts~n", [Poem]),
io:format("~p~n", [atom_to_list(hello) ++ "!"]),
io:format("~p~n", [list_to_atom("hello")]),
io:format("~p~n", [integer_to_list(255, 16)]).It prints:
"Zürich"
[90,252,114,105,99,104]
6 7
Zürich | Zürich
6
ZÜRICH
["red","green","blue"]
[<<"spaced">>,<<"out">>]
<<"añil">> versus <<"añil"/utf8>>
<<"a binary string">>
Line one
indented line two
"hello!"
hello
"FF"The list "Zürich" has six elements, one per character (ü is code point 252), while the UTF-8 binary needs seven bytes because ü takes two. Two printing rules prevent garbled output. Use ~ts rather than ~s for text that may contain characters beyond Latin-1, and ~tp rather than ~p to print binaries as Unicode: plain ~p shows the raw bytes of añil as if each were a separate Latin-1 character. The string module is grapheme-aware and accepts lists or binaries, returning the same kind it was given.
Finally, conversions are explicit, with function names that say exactly what they do: atom_to_list/1, list_to_atom/1, integer_to_list/2 (with a base), binary_to_list/1 and so on. As in Elixir, atoms are never garbage-collected and the atom table has a fixed limit (about a million by default), so never call list_to_atom/1 on input from outside; list_to_existing_atom/1 is the safe alternative.
Shapes you will meet in real code
Because Erlang has so few kinds of term, its programmers rely on a small set of conventions to give data meaning. Recognising them makes library documentation and other people's code much easier to read.
Return values. A function that can fail returns {ok, Value} or {error, Reason}, where Reason is usually an atom (enoent, timeout, not_found) or a tagged tuple with details ({bad_header, Line}). A function that succeeds without producing anything returns the atom ok. Functions that look things up often return the value itself or the atom undefined or false; lists:keyfind/3, for example, returns the matching tuple or false. Read the documentation's type specification to see which convention a function follows.
Options lists. Many functions take a list of options in which a bare atom means "on" and a two-tuple sets a value. Opening a TCP socket looks like gen_tcp:connect(Host, Port, [binary, {active, false}, {packet, line}]). Such a list of {Key, Value} tuples is called a property list, and the proplists module reads them. Newer APIs increasingly take maps instead, such as #{timeout => 5000}.
Records. Older code, and much of OTP itself, uses records: tuples with named fields, declared with -record(user, {name, email}) and written #user{name = "Ana"}. A record is purely a compile-time convenience: at run time #user{name = "Ana", email = undefined} is just the tuple {user, "Ana", undefined}. Records are fast and still common, but maps are now the usual choice for new code that crosses module boundaries. (OTP 29 introduced native records, a new, real data type with named fields, as an experimental feature; expect it to mature over the next releases.)
Identifiers. Processes are identified by pids, which print as <0.89.0>; unique tokens come from make_ref() and print as #Ref<...>. You cannot write them as literals in source code, but you will see them constantly in shell output and logs.
Common mistakes
Misconception
"<= is less-than-or-equal." In Erlang it is =<. Writing X <= 3 produces a syntax error in an ordinary expression, because <= is reserved for binary comprehensions.
Misconception
"== is the normal equality test." It compares numbers by value and is fine for that, but =:= is what most Erlang code means by "equal": same type and same value. 1 =:= 1.0 is false, which avoids subtle bugs when integers and floats mix.
Misconception
"A variable in a pattern always binds a new value." Only unbound variables do. A variable that already has a value is compared, so {Expected, Points} in a case matches only tuples whose first element equals Expected.
Misconception
"Strings and binaries are interchangeable." "abc" =:= <<"abc">> is false: one is a list, the other a binary. Many library functions accept either, but pattern matching and equality do not convert. Decide which representation each part of your program uses, and convert at the boundaries.
Exercises
1. Terms, variables and pattern matching
Warm-upComputationalWhat does io:format("~p~n", [10 div 3 + 10 rem 3]) print?
2. Terms, variables and pattern matching
Warm-upComputationalWhat is the value of 1 =:= 1.0?
3. Terms, variables and pattern matching
CoreComputationalAfter [_A, _B | C] = [1, 2, 3, 4], what does io:format("~p~n", [C]) print?
4. Terms, variables and pattern matching
CoreComputationalWhich of these matches raises a badmatch error? (Assume no variable is bound beforehand.)
5. Terms, variables and pattern matching
CoreComputationalWhat does this print, given that value() returns 10?
Limit = 10,
R = case {limit, value()} of
{limit, Limit} -> at_limit;
{limit, _} -> other
end,
io:format("~p~n", [R]).
6. Terms, variables and pattern matching
CoreComputationallength("añil") is 4. What is byte_size(<<"añil"/utf8>>)?
7. Terms, variables and pattern matching
Warm-upHumanWhich of these are atoms? List their letters.
- A:
ok - B:
'Ok' - C:
Ok - D:
"ok" - E:
true - F:
'hello world'
8. Terms, variables and pattern matching
StretchComputationalWhat does io:format("~p~n", [lists:sort([b, 2, "a", {x}])]) print?
Further reading and resources
- Data typesThe reference manual's chapter on every kind of term.
- ExpressionsPattern matching, operators, term comparison and the order of evaluation.
- The string moduleGrapheme-aware string functions that accept both lists and binaries.
- The erlang moduleThe built-in functions (BIFs), from is_atom/1 to tuple_size/1.