Modern Erlang tour

The language grows, and a course written a few releases ago teaches forms that are no longer the shortest way to say a thing. This tour collects the parts of Erlang that are new in OTP 25 to 27 and worth using every day: the doc attributes, the maybe expression, map comprehensions, the json module and persistent_term. Everything here runs on the OTP 27 of the course.

Specs and docs

A -type directive names a type, a -spec attaches one to a function, and -export_type makes the type usable from another module. A type that a spec uses is part of the module's interface, so it is exported; a type that stays inside is not, and Dialyzer warns about an exported function whose spec mentions a type the module keeps private. The documentation attributes are -doc and -moduledoc, and since OTP 27 their text can be a triple quoted string:

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([main/0, safe_div/2, first_number/1]). -export_type([result/0]). -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. main() -> io:format("safe_div(10, 2): ~p~n", [safe_div(10, 2)]), io:format("safe_div(10, 0): ~p~n", [safe_div(10, 0)]), io:format("first_number([1, 2]): ~p~n", [first_number([1, 2])]), io:format("first_number([]): ~p~n", [first_number([])]).

erlc modern.erl

erl -noshell -eval 'modern:main(), halt().'

safe_div(10, 2): {ok,5.0} safe_div(10, 0): {error,division_by_zero} first_number([1, 2]): {ok,1} first_number([]): error

The spec is a promise 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 named type keeps the spec short and gives the reader one place to change. The typespecs lesson covers the rest of the syntax, and -doc is what the documentation lesson turns into a page.

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, so no compile flag is needed here:

In first_number/1 the pattern [First | _] matches only a non-empty list. For an empty one the match fails, the else clause turns the failure into error, and the happy path stays at one level of indentation. Without maybe the same function is a case around a case, and the interesting branch disappears into the nesting.

New in OTP 27

The standard library keeps growing, and a few additions remove a dependency or a line of noise. The json module encodes and decodes JSON since OTP 27, so a fresh node needs no package for it. A map comprehension builds a map in one expression. persistent_term stores a term that is read far more often than it is written. A sigil such as ~"text" writes a binary, and a triple quoted string writes text with newlines in it:

otp27.erl

-module(otp27). -export([main/0]). main() -> Json = iolist_to_binary(json:encode(#{name => <<"Ada">>})), io:format("json: ~p~n", [Json]), Squares = #{N => N * N || N <- [1, 2, 3]}, io:format("map comprehension: ~p~n", [Squares]), persistent_term:put({?MODULE, port}, 8080), io:format("persistent term: ~p~n", [persistent_term:get({?MODULE, port})]), io:format("sigil: ~p~n", [~"hello"]), io:format("triple quoted: ~p~n", [""" one two """]).

erlc otp27.erl

erl -noshell -eval 'otp27:main(), halt().'

json: <<"{\"name\":\"Ada\"}">> map comprehension: #{1 => 1,2 => 4,3 => 9} persistent term: 8080 sigil: <<"hello">> triple quoted: "one\ntwo"

json:encode/1 answers iodata and not a binary, which is why the program wraps it in iolist_to_binary/1; the JSON lesson has the full story. A sigil does not interpolate in Erlang, and ~b"..." and ~s"..." choose a binary or a string. A triple quoted string keeps its newlines but drops the indentation of the closing line, so the same text formats well inside a module. persistent_term is for configuration that changes at deploy time: a write copies the term for every process, so it is not a cache that a request path updates.

Dialyzer

Dialyzer reads the beams 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 can really reach that state, even when the test suite never did. The first run builds a PLT, a cache of the analysed OTP applications, which takes minutes; later runs take seconds:

rebar3 dialyzer

The rules that keep the output clean: give every exported function a spec, export every type the specs of exported functions mention, 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 rather than once a year. The Dialyzer lesson builds the PLT by hand and reads the warning line.

Together with EUnit and the supervision of the OTP chapter, 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 the runtime for the running node.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. 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.

  2. What does -export_type do?

    Answer

    Lets another module use the type in its specs

    A type used by an exported function is part of the interface, and Dialyzer warns when it is private.

  3. What does the ?= operator do in a maybe block?

    Answer

    Matches a pattern and jumps to else on a mismatch

    Each ?= step continues the happy path or hands the failing value to else.

  4. Since which release is maybe enabled by default?

    Answer

    OTP 27

    It arrived in OTP 25 behind a feature flag and became the default in OTP 27.

  5. Which release added the json module to the standard library?

    Answer

    OTP 27

    Before OTP 27 a project needed a package such as jiffy or jsx for JSON.

  6. When is persistent_term the right choice?

    Answer

    For a value read often and written almost never

    A write copies the term for all processes, so the read side is what it optimises.

  7. What does this module print? -module(q1). -export([main/0]). -export_type([result/0]). -type result() :: {ok, integer()} | {error, zero}. -spec twice(integer()) -> result(). twice(0) -> {error, zero}; twice(N) -> {ok, N * 2}. main() -> io:format("~p ~p~n", [twice(4), twice(0)]).

    Answer

    {ok,8} {error,zero}

    The first clause matches zero and the second doubles every other integer.

  8. What does this module print? -module(q2). -export([main/0]). main() -> maybe [First | _] ?= [7, 8], io:format("~p~n", [First]) else _ -> io:format("empty~n") end.

    Answer

    7

    The list matches the pattern, so the happy path binds First to its head and prints it.

  9. What does this module print? -module(q3). -export([main/0]). main() -> io:format("~p~n", [#{N => N * N || N <- [1, 2, 3]}]).

    Answer

    #{1 => 1,2 => 4,3 => 9}

    A map comprehension builds a map whose keys are the values of the generator.

  10. What does this module print? -module(q4). -export([main/0]). main() -> persistent_term:put({?MODULE, port}, 9000), io:format("~p ~p~n", [persistent_term:get({?MODULE, port}), persistent_term:get({?MODULE, host}, none)]).

    Answer

    9000 none

    The first key was written, and the second call uses the default of the two argument form.

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.

Автор статьи: Arthur Isaev