Modules in Elixir

A module is the namespace of a program in Elixir: it groups functions under a name and compiles into one file of bytecode. Every function the course has written so far already lived in a module, because def only exists inside defmodule. This lesson takes the module apart: its name, its functions, the private ones, the ones nested under it, and the file the compiler writes.

defmodule

The module opens with defmodule and a capitalised name, holds its functions, and closes with end. A compiled source file has the extension .ex and declares modules without calling them:

math.ex

defmodule Math do def double(n), do: n * 2 def square(n), do: n * n end

The two functions are public, so a caller outside the module reaches them with the module name, a dot and the arguments. The compiler turns the file into one .beam file, and the virtual machine loads that file when the module is first called:

elixirc math.ex

ls Elixir.Math.beam

Elixir.Math.beam

elixir -e "IO.puts(Math.double(21))"

42

The file name carries the Elixir. prefix that the atoms lesson explained: the module Math is the atom :"Elixir.Math" at run time, and the beam file is named after it.

A module is a value

A module name is an atom, and a module is not a namespace the compiler erases: it is a value the program can pass, compare and inspect. __MODULE__ inside a module is that value, and a script can define the module and call it in the same file:

use_math.exs

defmodule Calc do def double(n), do: n * 2 def square(n), do: n * n end IO.puts(Calc.double(21)) IO.puts(Calc.square(5))

elixir use_math.exs

42
25

The script is a whole program: it defines the module and calls it. A module defined this way lives in memory for the run and writes no file, which is why the course uses scripts for examples and .ex files for code worth keeping.

Nested modules

A module declared inside another one gets the outer name as a prefix. Store.Item is a module of its own, with the full name of the path, and the outer module is not its parent in any other sense: no function of Store is visible inside Item:

nested.exs

defmodule Store do def welcome, do: "welcome" defmodule Item do def price, do: 99 end end IO.puts(Store.welcome()) IO.puts(Store.Item.price()) IO.puts(Store.Item == Store.Item)

elixir nested.exs

welcome
99
true

The last line is true because Store.Item is one atom, the same value every time it is written. Nesting keeps related modules under one name and gives the reader a hint about where the code lives; it does not create a scope for functions, which is a difference from a class in an object-oriented language.

defp inside the module

A function declared with defp is private to its module. The public function is the contract, the private one is a step of it, and a caller outside the module cannot reach the private name at all:

private.exs

defmodule Cart do def total(prices), do: sum(prices, 0) defp sum([], acc), do: acc defp sum([price | rest], acc), do: sum(rest, acc + price) end IO.puts(Cart.total([10, 20, 30]))

elixir private.exs

60

The recursive helper is a detail of total/1, and the module can change it without breaking a caller. A private function is not hidden from the documentation tools by accident: it is a statement that the name is not part of the contract, which is the same idea a library module uses for every step it does not want to promise.

The .beam the compiler writes

One module becomes one .beam file, and the file holds the compiled functions, the documentation and the module attributes. mix compile writes them into _build, and mix release packages them for a server. The file is tied to the Erlang version that compiled it, which is why a program deploys source or a release rather than a loose beam. The running code lesson compares the three commands that produce it.

The mistake: a private call from outside

A private function does not exist for a caller outside the module. Calling it raises UndefinedFunctionError, and the message says the function is undefined or private, which is exactly the point:

privcall.exs

defmodule Cart do def total(prices), do: sum(prices, 0) defp sum([], acc), do: acc defp sum([price | rest], acc), do: sum(rest, acc + price) end IO.puts(Cart.sum([10, 20], 0))

elixir privcall.exs

** (UndefinedFunctionError) function Cart.sum/2 is undefined or private
Cart.sum([10, 20], 0)
privcall.exs:8: (file)

The fix is the public function, Cart.total/1, which starts the accumulator and calls the private helper itself. When a helper really is part of the contract, make it public and document it; the compiler cannot guess which one a caller meant.

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.

Questions

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

  1. What does defmodule do?

    Answer

    It names a group of functions and compiles them into one module

    A module is the namespace of the functions, and the compiler writes one beam for it.

  2. What is the difference between def and defp?

    Answer

    def is reachable from outside the module, defp only from inside it

    A private function is a step of the module, not part of its contract.

  3. What is the full name of the module declared inside Store as defmodule Item?

    Answer

    Store.Item

    A nested declaration takes the outer name as a prefix.

  4. What file does elixirc math.ex write for defmodule Math?

    Answer

    Elixir.Math.beam

    The beam is named after the atom of the module, which carries the Elixir. prefix.

  5. What does this program print? defmodule Math do def double(n), do: n * 2 end IO.puts(Math.double(5))

    Answer

    10

    The call reaches the public function, and 5 doubled is 10.

  6. What does this program print? defmodule Hello do def name, do: __MODULE__ end IO.inspect(Hello.name())

    Answer

    Hello

    __MODULE__ is the atom of the module, and inspect prints it as the alias.

  7. What does this program print? defmodule Store do defmodule Item do def price, do: 99 end end IO.puts(Store.Item.price())

    Answer

    99

    The nested module is reached through its full name and its public function runs.

  8. What does this program print? defmodule Store do defmodule Item do def price, do: 99 end end IO.puts(Atom.to_string(Store.Item))

    Answer

    Elixir.Store.Item

    The module name is an atom, and its full string form starts with Elixir.

  9. What does this program print? defmodule A do def hi, do: "hi" end IO.puts(A.hi())

    Answer

    hi

    IO.puts/1 prints the binary without its quotes.

  10. What does this program print? defmodule A do def double(n), do: n * 2 def square(n), do: n * n end IO.puts(A.double(3) + A.square(3))

    Answer

    15

    The double gives 6, the square gives 9, and the sum is 15.

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