Cover by Francesco Cesarini, Simon Thompson

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

Modules

Functions are grouped together in modules. A program will often be spread across several modules, each containing functions that are logically grouped together. Modules consist of files with the .erl suffix, where the file and module names have to be the same. Modules are named using the –module(Name) directive, so in Example 2-2, the demo module would be stored in a file called demo.erl.

Example 2-2. A module example

-module(demo).
-export([double/1]).

% This is a comment.
% Everything on a line after % is ignored.

double(Value) ->
  times(Value, 2).
times(X,Y) ->
  X*Y.

The export directive contains a list of exported functions of the format Function/Arity. These functions are global, meaning they can be called from outside the module. And finally, comments in Erlang start with the percent symbol (%) and span to the end of the line. Make sure you use them everywhere in your code!

Global calls, also called fully qualified function calls, are made by prefixing the module name to the function. So, in Example 2-2, calling demo:double(2) would return 4. Local functions can be called only from within the module. Calling them by prefixing the call with the module name will result in a runtime error. If you were wondering what math:sqrt/1 did in Example 2-1, it calls the sqrt (square root) function from the math module, which comes as part of the Erlang standard distribution.

Functions in Erlang are uniquely identified by their name, their arity, and the module in which they are defined. ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required