Typespecs

Erlang is dynamically typed, and a function accepts whatever it is given until a pattern says otherwise. A typespec is the documentation of that intention in a form a tool can read: -type names a shape, -spec states what a function takes and returns, and -callback states what a behaviour asks of a module. The compiler reads them for documentation; the Dialyzer lesson reads them as claims to prove.

A type

A type is a name for a set of values. -type defines one, and -export_type lets another module use it in a spec. non_neg_integer() is a built-in type of the language, and the union price() | unknown is a type of its own. This module names a price and sums a list of them:

prices.erl

-module(prices). -export([main/0, total/1]). -export_type([price/0]). -type price() :: non_neg_integer(). -spec total([price()]) -> price(). total(Prices) -> lists:sum(Prices). main() -> io:format("~p~n", [total([2, 4, 6])]).

erlc prices.erl

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

12

The type costs nothing at run time: it is compiled into the documentation of the module and nothing else. Its value is in the reader of the spec and in the tools: a caller of total/1 sees [price()] -> price() in the editor, and Dialyzer can ask whether the body really returns a price().

A spec

-spec gives names to the arguments and states the result. A function that divides answers a float, even when both arguments are integers, because / always produces a float; the spec says so, and the body agrees:

fraction.erl

-module(fraction). -export([main/0, half/1]). -spec half(number()) -> float(). half(Number) -> Number / 2. main() -> io:format("~p~n", [half(5)]).

erlc fraction.erl

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

2.5

The spec sits right above the function and repeats its name and arity; a spec whose arity names no function is the mistake to avoid. Named arguments are optional but make a long contract readable: -spec total(Prices :: [price()]) -> price().. The functions lesson covers the head that the spec describes.

A callback

A behaviour is a contract between a generic module and the modules that plug into it. -callback states one function of that contract, and a module that declares -behaviour(store) promises to export every callback. OTP itself is a set of behaviours: gen_server, supervisor and application are the ones this course uses:

store.erl

-module(store). -callback put(Key :: term(), Value :: term()) -> ok. -callback get(Key :: term()) -> {ok, term()} | error.

erlc store.erl

The module compiles and has no functions of its own; its whole content is the contract. A module that claims the behaviour is compiled after this one, so store.beam must be on the code path: erlc -pa . memory_store.erl. A missing callback is a warning, and a project with warnings as errors stops there. The GenServer lesson writes the callbacks of a real OTP behaviour.

What a spec cannot do

A spec is a claim, not a check. erlc stores it and says nothing about it; a module with a spec that says integer() and a body that returns 2.5 compiles and runs, and the wrong claim is visible only to a tool that compares the two. Dialyzer makes that comparison, and its report names the line: Invalid type specification for function half/1.

So the rule is to write the spec the body really has, not the one the author meant. number() -> float() is honest for half/1 and integer() -> integer() is wrong twice: `/` returns a float, and the argument may be a float as well. The Dialyzer lesson runs the check on a project and reads the warning.

Questions

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

  1. What does -type price() :: non_neg_integer(). do?

    Answer

    Names a type that specs may use

    A type is a name for a set of values; it has no run-time effect and is used in specs and docs.

  2. Why is -export_type([price/0]) needed?

    Answer

    So another module may use the type in its own spec

    A type stays private to its module unless it is exported, and a spec elsewhere cannot name it otherwise.

  3. What does a -spec describe?

    Answer

    The arguments and result of one function

    A spec names one function by name and arity and states the types it takes and returns.

  4. What does a -callback describe?

    Answer

    One function a behaviour expects of a module

    A behaviour lists callbacks, and a module that declares the behaviour must export them.

  5. What does this module print? -module(q1). -export([main/0]). -spec double(integer()) -> integer(). double(X) -> X * 2. main() -> io:format("~p~n", [double(21)]).

    Answer

    42

    A spec changes nothing at run time; the function multiplies 21 by 2.

  6. What does this module print? -module(q2). -export([main/0]). -spec half(number()) -> float(). half(X) -> X / 2. main() -> io:format("~p~n", [half(5)]).

    Answer

    2.5

    The / operator returns a float, and the spec agrees; nothing checks the types at run time.

  7. What does this module print? -module(q3). -export([main/0]). -type result() :: {ok, integer()} | error. -spec parse(term()) -> result(). parse(N) when is_integer(N) -> {ok, N}; parse(_Other) -> error. main() -> io:format("~p~n", [parse(7)]), io:format("~p~n", [parse(nope)]).

    Answer

    {ok,7} / error

    The guard sends the integer to the first clause and every other term to error, exactly as the type says.

  8. What does this module print? -module(q4). -export([main/0]). -type pair() :: {atom(), integer()}. -spec pair() -> pair(). pair() -> {port, 5432}. main() -> io:format("~p~n", [pair()]).

    Answer

    {port,5432}

    The type names the tuple shape, and the function returns a value of that shape.

  9. Which tool proves that a spec matches the body of the function?

    Answer

    Dialyzer

    The compiler stores the spec; Dialyzer compares it with the values the body can return.

  10. A spec that says integer() for a function that returns 2.5 is what?

    Answer

    A wrong claim that compiles and runs until Dialyzer reports it

    A spec is not checked by the compiler, so the module runs and only Dialyzer names the wrong specification.

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