Chapter 6Modules and Named Functions

  • Modules, the basic unit of code

  • Defining public and private named functions

  • Guard clauses

  • Module directives and attributes

  • Calling functions in Erlang modules

Once a program grows beyond a couple of lines, you’ll want to structure it. Elixir makes this easy. You break your code into named functions and organize these functions into modules. In fact, in Elixir named functions must be written inside modules.

Let’s look at a simple example. Navigate to a working directory and create an Elixir source file called times.exs.

mm/times.exs
 
defmodule​ Times ​do
 
def​ double(n) ​do
 
n * 2
 
end
 
end

Here we have a module named Times. It contains a single function, double. Because our function takes a single ...

Get Programming Elixir now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.