Modules

  1. Compilation
  2. Scripted mode
  3. Named functions
  4. Function capturing
  5. Default arguments

In Elixir we group several functions into modules. We’ve already used many different modules in the previous chapters such as the String module:

iex> String.length("hello")
5

In order to create our own modules in Elixir, we use the defmodule macro. We use the def macro to define functions in that module:

iex> defmodule Math do
...>   def sum(a, b) do
...>     a + b
...>   end
...> end

iex> Math.sum(1, 2)
3

In the following sections, our examples are going to get longer in size, and it can be tricky to type them all in the shell. It’s about time for us to learn how to compile Elixir code and also how to run Elixir scripts.