Modern Erlang tour
Types and specs
A -type directive names a type, a -spec attaches one to a function, and a -doc string documents it. The compiler ignores all three at run time; they exist for the reader and for Dialyzer, which checks the calls without running the code. Since OTP 27 a documentation block is a triple quoted string, and the doc attribute takes a normal string. Save this module as modern.erl.
-module(modern).
-moduledoc """
A small tour of the OTP 27 language: specs, the maybe expression,
map comprehensions and the json module of the standard library.
""".
-export([safe_div/2, first_number/1, encode/1, config/1]).
-type result() :: {ok, number()} | {error, atom()}.
-doc "Divides two numbers; a zero divisor is an error value, not a crash.".
-spec safe_div(number(), number()) -> result().
safe_div(_A, 0) ->
{error, division_by_zero};
safe_div(A, B) ->
{ok, A / B}.
-doc "Answers the head of the list, or error for an empty one.".
-spec first_number(list()) -> {ok, term()} | error.
first_number(List) ->
maybe
[First | _] ?= List,
{ok, First}
else
_ ->
error
end.
-doc "Encodes a map as a JSON binary.".
-spec encode(map()) -> binary().
encode(Map) ->
iolist_to_binary(json:encode(Map)).
-doc "Reads a persistent term, or undefined when the key is unset.".
-spec config(atom()) -> term().
config(Key) ->
persistent_term:get({?MODULE, Key}, undefined).
A spec is a promise about the arguments and the answer, and it is checked in both directions: a call with an argument outside the declared type is a warning, and a body that can return a value outside the declared answer is a warning too. The result type above is a named type, which keeps the spec short and gives the reader one place to change.
erlc modern.erl
erl
1> modern:safe_div(10, 2).
{ok,5.0}
2> modern:safe_div(10, 0).
{error,division_by_zero}
The spec says number() for both arguments, so a call with an atom is a Dialyzer warning; the clause that matches zero makes the error value part of the contract, so the caller has to handle it.
The maybe expression
A chain of calls that can each fail usually turns into nested case expressions. maybe flattens the chain: each step is bound with ?=, and the first value that does not match jumps to the else block. The feature arrived in OTP 25 behind a flag and is on by default since OTP 27.
erl
1> modern:first_number([1, 2, 3]).
{ok,1}
2> modern:first_number([]).
error
The pattern [First | _] only matches a non-empty list, so an empty one fails the match and the else clause turns the failure into error. Without maybe the same function is a case around a case, and the happy path disappears into the nesting.
New in the library
The standard library keeps growing, and a few additions are worth knowing. The json module encodes and decodes JSON since OTP 27, so a fresh node needs no dependency for it. A map comprehension builds a map in one expression. persistent_term stores a value that is read far more often than it is written, and a read of it costs nothing at run time once the term is in place.
erl
1> modern:encode(#{name => <<"Ada">>}).
<<"{\"name\":\"Ada\"}">>
2> #{N => N * N || N <- [1, 2, 3]}.
#{1 => 1,2 => 4,3 => 9}
3> persistent_term:put({modern, port}, 8080), modern:config(port).
8080
4> modern:config(release).
undefined
json:encode answers iodata and not a binary, which is why encode/1 wraps it in iolist_to_binary; lesson 30 has the full story. json:encode turns a charlist into an array of code points, so pass binaries for text. persistent_term is for configuration that changes at deploy time: a write is expensive because every process has to update its reference to the term, so it is not a cache that a request path updates.
Dialyzer
Dialyzer reads the beam files and the specs and looks for calls that can never return a sensible value. It has no false positives by design: a warning means the code really can reach that state, even if the test suite never did. That is why the tool is trusted in production and why a project keeps its specs honest.
rebar3 dialyzer
The first run builds a PLT, a cache of the analysed OTP applications, and it takes minutes; later runs take seconds. The rebar3 task reuses the PLT under _build. The rules that keep the output clean: give every exported function a spec, do not hide a wrong type behind a catch-all clause, use -opaque for a type that callers must not look inside, and run the tool on every change, not once a year.
Together with EUnit of lesson 26 and the supervision of lesson 35, this is the toolchain of a modern Erlang project: rebar3 for the build and the release, EUnit and Common Test for the behaviour, Dialyzer for the types, and observer for the running node.
Next: Hero roadmap: the whole course on one page
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What is the purpose of a
-spec?Answer
To declare the argument and answer types for the reader and Dialyzer
The spec is a checked contract; the compiler stores it in the beam for Dialyzer.
-
What does a
-typedirective do?Answer
Names a type for reuse in specs
A named type keeps specs short and gives one place to change the definition.
-
Which property makes Dialyzer trusted in production?
Answer
It has no false positives
A Dialyzer warning means the code can really reach the reported state.
-
What does the
?=operator do in amaybeblock?Answer
Matches a pattern and jumps to
elseon a mismatchEach
?=step continues the happy path or hands the failing value toelse. -
Since which release is
maybeenabled by default?Answer
OTP 27
It arrived in OTP 25 behind a feature flag and became the default in OTP 27.
-
What does a map comprehension look like?
Answer
#{K => V || K <- L}The
#{K => V || ...}form builds a map in one expression. -
Which release added the
jsonmodule to the standard library?Answer
OTP 27
Before OTP 27 a project needed jiffy or jsx for JSON.
-
What does
json:encode/1answer?Answer
Iodata
The result is iodata, so
iolist_to_binaryturns it into one binary. -
When is
persistent_termthe right choice?Answer
For a value read often and written almost never
Writes copy the term for all processes, so the read side is what it optimizes.
-
What does an
-opaquetype hide?Answer
The internals of a type that callers must not inspect
Dialyzer refuses to let other modules look inside an opaque type, which keeps the representation free to change.
The examples on this page were compiled and run with Erlang/OTP 27 (erts-15.2.7.14) on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev