O'Reilly logo

Erlang Programming by Francesco Cesarini, Simon Thompson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required