Skip to content
LumenaryAcademy
Foundations 45 min

Getting started with Erlang

Why a telephone company invented a programming language, what the BEAM and OTP are, and your first programs in the shell, as escripts and as compiled modules.

Code tested · 3AI-draftedAwaiting review by a computer scientist
MotivationH

A language for systems that never stop

In the mid-1980s, Ericsson built telephone exchanges: machines that connect calls for a whole city. Their software had requirements that most programs still do not face. An exchange handles tens of thousands of calls at the same time, each of them a small, independent conversation with its own state. Hardware fails, and software has bugs, but a fault in one call must never drop the others. And the exchange must keep running for years; new features and bug fixes have to be installed while calls are in progress.

The languages of the day were poorly suited to this. Ericsson's Computer Science Laboratory set out to find something better, and what they ended up with was a new language whose central ideas came straight from those requirements:

  • Concurrency is cheap and built in. Every call can be its own lightweight process, and a single machine can run hundreds of thousands of them.
  • Processes share nothing. They communicate only by sending messages, so one process cannot corrupt another's data.
  • Failure is normal. Processes can watch each other, and when one fails, another can restart it in a clean state. Programs are written to "let it crash" instead of guarding against every conceivable error.
  • Code can be replaced while it runs. A new version of a module can be loaded into a live system.

Those ideas turned out to fit far more than telephones. Erlang now runs message brokers, chat systems, databases, game servers and payment platforms: anything with many concurrent users and a need to stay up. It also gave the world the BEAM virtual machine, on which newer languages such as Elixir and Gleam run. Learning Erlang means learning the original, and still clearest, expression of these ideas.

History & global context

From Ericsson to open source

Erlang's design began in 1986, when Joe Armstrong started experimenting with ways to program telephony at Ericsson. Robert Virding and Mike Williams soon joined him, and the three are usually credited as the language's creators. The first implementation was an interpreter written in Prolog, which is why Erlang's syntax still looks like Prolog's: variables start with capital letters, clauses end with full stops, and pattern matching is everywhere. The name honours the Danish mathematician Agner Krarup Erlang, a founder of the theory of telephone traffic, and conveniently also reads as "Ericsson language".

The Prolog interpreter was far too slow for real switches, so the team built virtual machines: first JAM, then BEAM, which became the standard runtime in the late 1990s. In 1996 Ericsson packaged the language with its libraries and design patterns as OTP, and Erlang was used in products such as the AXD301 ATM switch, announced in 1998.

That same year, Ericsson decided to favour widely used, non-proprietary languages for new products, and in December 1998 Erlang was released as open source. The decision that looked like an ending was a beginning. Outside Ericsson, Erlang found users who needed exactly what it offered: RabbitMQ, ejabberd, CouchDB and Riak were written in it, and WhatsApp built its messaging servers on it. Ericsson itself kept developing and using Erlang, and still leads OTP's development today.

The runtime kept improving underneath: support for multi-core processors arrived in 2006, a just-in-time compiler (BeamAsm) in OTP 24 in 2021, and documentation written in the code itself in OTP 27. A new major release ships every year around May; Erlang/OTP 29, used for this course, was released in May 2026. Joe Armstrong died in 2019, and his paper A history of Erlang, linked below, remains the best account of the design in his own words. The Erlang Ecosystem Foundation, founded the same year, supports the wider community of BEAM languages.

DefinitionsH

The BEAM, OTP and the tools you install

Definition— BEAM and ERTS

The BEAM is the virtual machine that runs compiled Erlang (and Elixir, and Gleam) code. Together with the memory manager, schedulers and built-in functions it forms ERTS, the Erlang Run-Time System. The BEAM runs one scheduler thread per CPU core and spreads lightweight processes across them, switching between processes preemptively.

Definition— OTP

OTP is the Erlang distribution as a whole: the runtime, the compiler, the standard libraries (stdlib, kernel and dozens of others), tools such as the debugger and Dialyzer, and the design principles: behaviours such as gen_server and supervisor that structure real systems. "Erlang/OTP 29" names a version of the whole bundle.

Installing Erlang/OTP gives you three commands you will use from day one:

CommandWhat it does
erlstarts the runtime with an interactive shell
erlccompiles .erl source files to .beam bytecode files
escriptruns a single-file Erlang script

The downloads page offers installers for Windows and source releases; on macOS and Linux most people use a package manager or a version manager such as kerl, asdf or mise, which build any OTP version from source. Projects are built with rebar3, Erlang's standard build tool, which you will meet in the last lesson. To see which release you have, ask the runtime itself:

text
$ erl -noshell -eval 'io:format("~s~n", [erlang:system_info(otp_release)]), halt().'
29
ComputationC

The shell

Type erl and you get the shell. Here is a session from the toolchain used for this course, with each result as the shell printed it:

text
Erlang/OTP 29 [erts-17.1.1] [source] [64-bit] [smp:20:20] [ds:20:20:10] [async-threads:1] [jit:ns]

Eshell V17.1.1 (press Ctrl+G to abort, type help(). for help)
1> 2 + 3 * 4.
14
2> X = 10.
10
3> X = 11.
** exception error: no match of right hand side value 11
4> f(X).
ok
5> X = 11.
11
6> lists:reverse([1, 2, 3]).
[3,2,1]
7> string:uppercase("bonjour").
"BONJOUR"
8> self().
<0.89.0>

(The numbers in the banner describe the machine: smp:20:20 means 20 schedulers for 20 cores.) Three things surprise every newcomer.

First, every expression ends with a full stop. The shell waits until it sees one, so if nothing happens after you press Enter, you probably forgot it.

Second, variables can be bound only once. X = 10 binds X; X = 11 is not an assignment but a match of 11 against the value 10, which fails. You will study this in the next lesson. In the shell, f(X) forgets a binding and f() forgets them all, so you can experiment.

Third, functions are called as module:function(Arguments). lists:reverse/1 lives in the lists module of the standard library and string:uppercase/1 in string. Function names are written with their arity, the number of arguments: lists:reverse/1 and lists:reverse/2 are different functions.

Useful shell commands include help(), c(Module) to compile and load a module, h(lists, reverse) to show a function's documentation, examples included, b() to show bindings and q() to quit. Ctrl+G opens a small job-control menu, from which q also quits.

Worked examplesH

Your first programs

The quickest way to run a complete program is an escript: a single source file whose main/1 function is called with the command-line arguments. Save this as hello.erl and run escript hello.erl:

erlang
#!/usr/bin/env escript
main(_Args) ->
    io:format("Hello, world!~n").

It prints:

text
Hello, world!

The first line lets Unix-like systems run the file directly once it is executable; escript ignores it. main(_Args) -> defines a function: the head, an arrow, then the body. The underscore at the start of _Args tells the compiler we deliberately ignore the argument, so it will not warn about an unused variable. io:format/1 prints a format string, in which ~n means a newline.

Erlang's punctuation is short but strict, and learning it early saves frustration. Think of it like written English:

  • a comma , separates expressions in a body, like "and then";
  • a semicolon ; separates the clauses of a function, case or if, like "or else";
  • a full stop . ends a whole function definition, like the end of a sentence.

Here is a program that uses all three, defines a second function and prints different kinds of values:

erlang
#!/usr/bin/env escript
main(_) ->
    Name = "Ingrid",
    io:format("Hello, ~s!~n", [Name]),
    io:format("~p~n", [{ok, [1, 2, 3], "text", <<"bytes">>, 3.5}]),
    io:format("25! = ~p~n", [factorial(25)]),
    io:format("~w versus ~p~n", ["abc", "abc"]),
    io:format("~8.3f|~-6s|~6b|~n", [3.14159, "left", 42]).

factorial(0) -> 1;
factorial(N) when N > 0 -> N * factorial(N - 1).

It prints:

text
Hello, Ingrid!
{ok,[1,2,3],"text",<<"bytes">>,3.5}
25! = 15511210043330985984000000
[97,98,99] versus "abc"
   3.142|left  |    42|

io:format/2 takes a format string and a list of arguments, one per directive. ~s prints a string, ~p "pretty prints" any value as Erlang syntax, ~w writes the raw term, and ~f, ~s and ~b (integer) take a field width and precision. The difference between ~w and ~p on "abc" is your first glimpse of a fact explored in the next lessons: an Erlang string is a list of character codes, and ~p shows such a list as text when it looks like text.

factorial/1 has two clauses, separated by a semicolon. Erlang tries them in order: the first matches only the argument 0; the second matches any N, but only when N > 0, a guard. And 25! is computed exactly: Erlang integers grow as large as needed and never overflow.

Finally, a taste of what Erlang is famous for. This script starts a hundred thousand processes, each of which computes one square and sends it back as a message:

erlang
#!/usr/bin/env escript
main(_) ->
    Parent = self(),
    N = 100000,
    [spawn(fun() -> Parent ! {square, I * I} end) || I <- lists:seq(1, N)],
    Total = collect(N, 0),
    io:format("Sum of the first ~p squares: ~p~n", [N, Total]).

collect(0, Sum) -> Sum;
collect(Left, Sum) ->
    receive
        {square, S} -> collect(Left - 1, Sum + S)
    end.

It prints:

text
Sum of the first 100000 squares: 333338333350000

spawn/1 starts a process running a function (a fun), Parent ! Message sends a message, and receive waits for one. The list comprehension [... || I <- lists:seq(1, N)] runs spawn once for each number. On a laptop the whole program takes well under a second, because a new process costs only a couple of kilobytes of memory. You will learn all of this properly in Processes, mailboxes and selective receive.

ExplanationH

Modules, compiling and loading

Escripts are convenient for small tools and for this course. Real Erlang code lives in modules, one per file, compiled to .beam files that the runtime loads. A module begins with attributes:

erlang
-module(hello).
-export([greet/1]).

greet(Name) ->
    io:format("Hello, ~s!~n", [Name]).

-module(hello). names the module, and the file must be called hello.erl. -export([greet/1]). lists the functions that other modules may call; everything else is private to the module. You can compile it from a terminal and run a function without a shell:

text
$ erlc hello.erl
$ ls
hello.beam  hello.erl
$ erl -noshell -eval 'hello:greet("Nkechi"), halt().'
Hello, Nkechi!

or compile and load it from inside the shell, where you can then call it directly:

text
1> c(hello).
{ok,hello}
2> hello:greet("Pita").
Hello, Pita!
ok
3> hello:module_info(exports).
[{greet,1},{module_info,0},{module_info,1}]

The ok after the greeting is the return value of io:format/2, which the shell prints. module_info/0,1 are added to every module by the compiler. When you edit hello.erl and run c(hello). again, the running system replaces the old code with the new without restarting: a small preview of hot code loading, which you will meet properly in the last lesson.

An escript may also declare -module(...) and -export(...), and it can use any library in OTP. Current OTP releases compile an escript before running it, so it runs at full speed, and the same compiler warnings apply as for modules.

Which should you use? Escripts suit small command-line tools and experiments: one file, nothing to install beyond Erlang. Anything bigger, with several modules, tests, dependencies or a long-running service, belongs in a rebar3 project, where each module has its own file and the build tool handles compiling, testing and packaging.

Common misconceptionsH

Common first misunderstandings

Misconception

"Erlang is a telecom language and nothing else." It was designed for telephony, but its strengths (massive concurrency, isolation, fault tolerance) are those of any server with many users. Message brokers, databases, chat services, game back ends and payment systems use it today.

Misconception

"Erlang is old, so it must be abandoned." Erlang/OTP ships a major release every year, with recent additions such as a JIT compiler, documentation attributes, a JSON module and new comprehension forms. Age here means three decades of hard-won experience with systems that must not stop.

Misconception

"The full stops, commas and semicolons are arbitrary." They follow one consistent rule: commas sequence expressions, semicolons separate alternative clauses, and a full stop ends a definition. Most syntax errors for beginners are a comma where a semicolon belongs, or a full stop too early.

Note

Elixir and Erlang share the BEAM, its processes and OTP, and they call each other's code freely. If you already know Elixir, much of this course will feel familiar; the Elixir course on this site covers the same runtime from the Elixir side.

Exercises

Exercises

1. Getting started with Erlang

Warm-upComputational

In this definition, which character belongs where the ? is?

sign(0) -> zero?
sign(N) when N > 0 -> positive;
sign(_) -> negative.
Choose one

2. Getting started with Erlang

CoreComputational

What does io:format("~p~n", [[72, 105]]) print? (72 and 105 are the character codes of H and i.)

3. Getting started with Erlang

CoreComputational

And what does io:format("~w~n", ["Hi"]) print?

4. Getting started with Erlang

Warm-upComputational

In a fresh shell you type X = 5. and then X = 6.. What happens?

Choose one

5. Getting started with Erlang

Warm-upComputational

With the lesson's definition

factorial(0) -> 1;
factorial(N) when N > 0 -> N * factorial(N - 1).

what is factorial(5)?

6. Getting started with Erlang

Warm-upHuman

You have a module in stats.erl and want a stats.beam file without starting a shell. Which command do you run?

Choose one

7. Getting started with Erlang

CoreHuman

Which statements are true? List their letters.

  • A: An escript's entry point is main/1, called with the command-line arguments.
  • B: Only functions listed in -export can be called from other modules.
  • C: A module named hello must be in a file named hello.erl.
  • D: Variable names start with a lowercase letter.
  • E: lists:reverse/1 and lists:reverse/2 are the same function.

Write elements separated by commas. Order and repeats don’t matter — just like in a set!

Further reading and resources