Modules & Functions

Functions are identified by name/arity: area/1 and area/2 are completely different functions.

7.1 Module structure

Functions are identified by name/arity: area/1 and area/2 are completely different functions.

-module(geometry).
-export([area/1, perimeter/1]).       % public API
-import(math, [pi/0]).                % optional: call pi() without math: (discouraged)
-define(SQUARE(X), X * X).            % macro
-vsn(1).                              % module version
-author("You").

area({square, Side}) -> ?SQUARE(Side);
area({rectangle, W, H}) -> W * H;
area({circle, R}) -> pi() * R * R.

perimeter({square, S}) -> 4 * S;
perimeter({rectangle, W, H}) -> 2 * (W + H);
perimeter({circle, R}) -> 2 * pi() * R.

7.2 Function clauses

Clauses are tried top to bottom; the first whose pattern (and guard) matches runs:

greet(english, Name) -> "Hello, " ++ Name;
greet(spanish, Name) -> "Hola, " ++ Name;
greet(_, Name) -> "Hi, " ++ Name.

7.3 Calling functions

geometry:area({square, 3}).            % remote (fully qualified) call
area({square, 3}).                     % local call (inside the module)
apply(geometry, area, [{square, 3}]).  % dynamic call
M = geometry, F = area, M:F({square, 3}).

7.4 Exports & other attributes

-export([f/1]).
-export_type([my_type/0]).
-compile(export_all).          % only for debugging (warns)
-compile({inline, [helper/1]}).
-on_load(init/0).
-behaviour(gen_server).
-record(person, {name, age}).
-include("defs.hrl").
-include_lib("kernel/include/file.hrl").
-deprecated([{old/1, "use new/1"}]).
-nifs([fast/1]).

7.5 Module info

geometry:module_info().
geometry:module_info(exports).
code:which(geometry).

7.6 Naming conventions

Modules and functions: snake_case atoms.

Variables: CamelCase.

Module file: my_module.erl.

Prefix modules with the application name in larger systems (myapp_server, myapp_sup).