100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Programming

Erlang Quick Reference

A cheat-sheet tour of Erlang's core data types, common built-in functions, the shell/module workflow, OTP gen_server callbacks, and the pattern-matching idioms you'll reach for every day.

PracticeBeginner10 min readJul 10, 2026
Analogies

Erlang Quick Reference

Erlang is a functional, concurrent programming language built at Ericsson to run fault-tolerant telecom switches that must stay up for years. Its process model, one process per unit of work, communicating only through message passing, makes it a natural fit for systems that need to keep running even when parts of them fail. This module is a fast-scanning cheat sheet: core data types, common built-in functions (BIFs), the shell-and-module development loop, the OTP gen_server callback contract, and the pattern-matching idioms that show up in almost every Erlang function you'll write.

🏏

Cricket analogy: Like an IPL double-header where two matches run on different grounds at once, an Erlang system runs thousands of lightweight processes concurrently, and a rain delay in Mumbai doesn't stop the Bangalore fixture.

Core Data Types

Atoms are constants that stand for themselves, ok, error, undefined, written lowercase or quoted with single quotes if they contain spaces or start with a capital. Tuples group a fixed number of related values, {ok, Value} or {error, Reason}, and are typically pattern-matched by shape. Lists are variable-length linked lists, [1, 2, 3], built from a head and tail, [H|T], and are the workhorse for sequences of unknown length. Binaries, <<1, 2, 3>> or <<"hello">>, hold raw byte sequences efficiently, ideal for network data and file contents. Maps, #{key => value}, are key-value structures introduced in OTP 17 for dynamic associative data. Records, defined with -record(person, {name, age}) and constructed as #person{name = "Ada", age = 36}, are compile-time syntactic sugar over tuples that give named-field access to fixed-shape data.

🏏

Cricket analogy: A player's scorecard line like {Kohli, 82, 53} is a fixed-shape tuple of name, runs, and balls faced, while the full list of every over bowled in the innings is a growing list you traverse ball by ball.

erlang
%% Atoms
Status = ok.
Error = 'this is an atom with spaces'.

%% Tuples
Point = {10, 20}.
Result = {ok, "success"}.

%% Lists
Numbers = [1, 2, 3, 4].
[Head | Tail] = Numbers.   %% Head = 1, Tail = [2,3,4]

%% Binaries
Bin = <<1, 2, 3>>.
TextBin = <<"hello">>.

%% Maps
Person = #{name => "Ada", age => 36}.
#{name := Name} = Person.  %% Name = "Ada"

%% Records
-record(person, {name, age}).
P = #person{name = "Ada", age = 36}.
P#person.age.               %% 36

Common Built-in Functions (BIFs)

Built-in functions, or BIFs, live in the erlang module but are auto-imported, so most can be called without the erlang: prefix. length/1 returns the number of elements in a list; is_list/1, is_atom/1, is_tuple/1, and friends are type-testing predicates commonly used in guards. list_to_binary/1 and binary_to_list/1 convert between list and binary representations of the same data. spawn/1 creates a new lightweight process from a fun and returns its process identifier (Pid); self/0 returns the Pid of the currently executing process, frequently sent to another process so it knows where to reply.

🏏

Cricket analogy: Just as an on-field umpire always has the snickometer and Hawk-Eye replay available without special setup, Erlang's BIFs like length/1 and self/0 are auto-imported from the erlang module and callable anywhere without a module prefix.

erlang
1> length([1,2,3]).
3
2> is_list([1,2,3]).
true
3> is_atom(ok).
true
4> list_to_binary("hi").
<<"hi">>
5> Pid = spawn(fun() -> io:format("hello from ~p~n", [self()]) end).
<0.85.0>
6> self().
<0.80.0>

Shell & Module Workflow

erl starts the Erlang shell, a read-eval-print loop where every expression ends with a period. c(module) compiles a module's source file (module.erl) in the current directory and loads the resulting beam file, making its exported functions callable as module:function(Args). l(module) reloads an already-compiled beam file without recompiling, useful after another tool rebuilt it. q() halts the runtime and exits the shell. This tight compile-load-call loop is how most Erlang development happens day to day, especially while exploring a new module's behavior interactively.

🏏

Cricket analogy: In the nets, a batsman like Rohit Sharma tweaks his backlift and immediately faces the next delivery to test the change, much like c(module) recompiles a .erl file and lets you call the updated function right away in the erl shell.

erlang
$ erl
Eshell 13.0

1> c(math_utils).
{ok,math_utils}
2> math_utils:square(5).
25
3> l(math_utils).   %% reload after editing the .beam externally
{module,math_utils}
4> q().
ok

c(module) both compiles module.erl and loads the result, so it must find a matching -module(module_name) attribute and the source file in the shell's current path (check with pwd() or add directories with code:add_path/1). If you only need to reload a beam file that another build tool already compiled, l(module) is faster since it skips recompilation.

OTP Behaviour Callbacks

The gen_server behaviour turns the boilerplate of a message-receiving loop into a small set of callbacks that OTP calls for you. init/1 runs when the process starts, typically via gen_server:start_link/3 or /4, and must return {ok, State} (or {stop, Reason} to abort startup). handle_call/3 receives {Request, From, State} for synchronous requests and normally returns {reply, Reply, NewState}, blocking the caller until a reply is sent. handle_cast/2 receives {Msg, State} for fire-and-forget asynchronous messages and returns {noreply, NewState} since there's no caller waiting. terminate/2 receives {Reason, State} and is the place to release resources like open file handles or sockets before the process exits.

🏏

Cricket analogy: In an ODI, the toss decision (init/1) sets up the innings, a fielding captain's request for a DRS review needs the umpire's reply (handle_call/3), the crowd's cheering (handle_cast/2) needs no response, and the post-match handshake (terminate/2) closes things out.

erlang
-module(counter).
-behaviour(gen_server).
-export([init/1, handle_call/3, handle_cast/2, terminate/2]).

init(InitialCount) ->
    {ok, InitialCount}.

handle_call(get_count, _From, State) ->
    {reply, State, State}.

handle_cast(increment, State) ->
    {noreply, State + 1}.

terminate(_Reason, _State) ->
    ok.

terminate/2 is not guaranteed to run. If a gen_server is killed abruptly (exit(Pid, kill)) or crashes in a way its supervisor doesn't cleanly stop, terminate/2 may never execute unless the process is trapping exits (process_flag(trap_exit, true)). Don't rely on terminate/2 alone for critical cleanup like releasing an external lock; pair it with monitors, links, or supervisor strategies for guaranteed resource recovery.

Pattern Matching, Guards & Operators

The = operator in Erlang is a pattern match, not an assignment: {ok, X} = {ok, 5} binds X to 5, while {ok, X} = {error, foo} raises a badmatch error because the shapes don't line up. Guards, the when clauses on function heads, restrict which clause matches based on type checks or comparisons, evaluated left to right with no side effects allowed. Equality has two flavors: == allows numeric coercion, so 1 == 1.0 is true, while =:= is strict about both value and type, so 1 =:= 1.0 is false. List comprehensions, [Expr || Pattern <- List, Condition], build a new list by mapping and filtering in one expression. ++ concatenates two lists, while -- removes the first occurrence of each element of the right-hand list from the left-hand list.

🏏

Cricket analogy: DRS ball-tracking demands an exact strict match, like =:=, between the predicted and actual trajectory, whereas a commentator's loose call of 'similar height' is closer to ==; a comprehension is like filtering the over-by-over list for deliveries clocked above 140 km/h.

erlang
%% Pattern matching & guards
classify(N) when N > 0 -> positive;
classify(N) when N < 0 -> negative;
classify(0) -> zero.

%% =:= vs ==
1 == 1.0.    %% true  (value equality, coerces types)
1 =:= 1.0.   %% false (value AND type equality)

%% List comprehension
Evens = [X || X <- lists:seq(1, 10), X rem 2 =:= 0].
%% Evens = [2,4,6,8,10]

%% ++ and --
[1,2,3] ++ [4,5].      %% [1,2,3,4,5]
[1,2,3,2] -- [2].      %% [1,3,2]
  • Atoms, tuples, lists, binaries, maps, and records are Erlang's core data types, each suited to a different shape of data.
  • BIFs like length/1, is_list/1, list_to_binary/1, spawn/1, and self/0 are auto-imported from the erlang module and callable without a prefix.
  • The erl shell plus c(module) to compile-and-load and module:function(Args) to call form the core interactive development workflow; l(module) reloads an already-compiled beam.
  • gen_server callbacks follow a strict contract: init/1 sets up state, handle_call/3 answers synchronous requests, handle_cast/2 handles fire-and-forget messages, and terminate/2 cleans up.
  • terminate/2 is not guaranteed to run on abrupt process kills unless the process is trapping exits, so don't rely on it alone for critical cleanup.
  • =:= checks value and type equality (1 =:= 1.0 is false) while == allows numeric coercion between integers and floats (1 == 1.0 is true).
  • List comprehensions, ++, and -- are idiomatic tools for building, combining, and subtracting lists in Erlang.

Practice what you learned

Was this page helpful?

Topics covered

#Programming#ErlangStudyNotes#ErlangQuickReference#Erlang#Quick#Reference#Core#StudyNotes#SkillVeris#ExamPrep