Typespecs

A typespec in Elixir is documentation the compiler understands: @spec states the arguments and the result of a function, and @type gives a name to a shape used in several specs. The runtime does not check them, but a reader does, and the tool of the next section reads them without running the program. A project that ships a library writes the specs its callers need.

A spec on a function

The spec sits above the function, names the types between the parentheses and gives the result after the arrow. number() covers integers and floats, and float() is narrower:

shapes.exs

defmodule Shapes do @type side :: number() @spec square(side) :: number() def square(x), do: x * x @spec area({:circle, number()}) :: float() def area({:circle, r}), do: :math.pi() * r * r end IO.inspect(Shapes.square(4)) IO.inspect(Shapes.area({:circle, 1}) |> Float.round(2))

elixir shapes.exs

16
3.14

The spec says nothing about the body: square/1 would still multiply if the spec named a string, and the callers would see the number. What the spec gives is a contract a reader and a tool can compare with the code, and an editor that shows the signature while a call is typed.

@type and the union

A shape that appears in several specs gets a name. A union separates alternatives with |, and a tuple type lists the elements in order:

@type point :: {number(), number()} @type shape :: {:circle, number()} | {:rect, number(), number()} | point()

A spec can then say @spec draw(shape()) :: :ok, and the reader sees the three shapes without opening the function. The built-in types are the ones of the language: integer(), float(), binary(), atom(), list(type), map() and no_return().

The tool that reads them

dialyzer reads the compiled beams and the specs and reports a call that cannot succeed, such as a function that always returns a binary used where the spec promises an integer. It is slow on the first run because it builds a PLT of the runtime, and a Mix project runs it with mix dialyzer after adding the dialyxir package. Hex and the network are not available in the environment of this course, so the tool is described here and not run.

The mistake: a spec for another arity

A spec is attached to a name and an arity. When the function has three arguments and the spec describes two, the compiler reports the spec as undefined before the program runs:

badspec.exs

defmodule Bad do @spec add(integer(), integer()) :: integer() def add(a, b, c), do: a + b + c end IO.inspect(Bad.add(1, 2, 3))

elixir badspec.exs

    error: spec for undefined function add/2
    │
  2 │ @spec add(integer(), integer()) :: integer()
    │ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    │
    └─ badspec.exs:2

** (CompileError) badspec.exs: cannot compile file (errors have been logged)
    (stdlib 6.2.2.5) lists.erl:2146: :lists.foldl/3

The fix is the third argument in the spec: @spec add(integer(), integer(), integer()) :: integer(). The error is a good example of what a spec buys: a change to the arity of a public function is caught at compile time even though no caller ran.

The programs on this page were run with Elixir 1.19.7 on Erlang/OTP 27 (erts 15.2.7.14), on Linux x86_64 in a Docker container. Dialyzer is not installed in that environment.

Questions

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

  1. What is a typespec in Elixir?

    Answer

    A description of the arguments and the result that a tool can read

    A spec is documentation with a type, read by Dialyzer and by editors, not enforced at run time.

  2. Which attribute states the type of a function?

    Answer

    @spec

    @spec names the arguments and the result of one function.

  3. Which attribute gives a name to a shape used in several specs?

    Answer

    @type

    @type defines a named type, such as a point or a shape union.

  4. What does number() include?

    Answer

    Integers and floats

    number() is the union of integer() and float().

  5. What does this program print? defmodule M do @spec double(integer()) :: integer() def double(n), do: n * 2 end IO.inspect(M.double(21))

    Answer

    42

    The spec does not change the call; 21 doubled is 42.

  6. What does this program print? defmodule M do @spec area({:circle, number()}) :: float() def area({:circle, r}), do: :math.pi() * r * r end IO.inspect(M.area({:circle, 1}) |> Float.round(2))

    Answer

    3.14

    The area of the unit circle is about 3.14159, rounded to 3.14.

  7. What does a spec for add/2 on a function with three arguments cause?

    Answer

    A compile error: spec for undefined function add/2

    A spec is matched to its name and arity at compile time.

  8. Which tool reads the specs and the compiled code to find impossible calls?

    Answer

    Dialyzer

    Dialyzer is the type analysis tool for Erlang and Elixir beams.

  9. Why is Dialyzer not run on this page?

    Answer

    Because it is not installed and needs the Hex package dialyxir plus a PLT

    The environment has no Hex and no network, so the page describes the tool and marks it.

  10. A spec names binary() but the function always returns an integer. What happens at run time?

    Answer

    The function returns the integer; the spec is not checked at run time

    Specs are not enforced by the runtime; Dialyzer is the tool that reports the mismatch.

Article author: Arthur Isaev