Modules, exports and imports
| The module header | |
| Call across modules | |
| Import selectively | |
| Where modules live |
The module header
A module starts with its name and its export list. The name must match the file name, and the export list is the module's public surface.
The behaviour attribute, covered in later lessons, declares the callbacks a module promises to implement.
-module(math_util).
-export([double/1, sum/1]).
double(X) -> X * 2.
Call across modules
Call another module with the colon: module name, colon, function name. The arguments follow in parentheses, and the result returns like any call.
The standard library is a set of modules like this, so lists:map and file:read_file are just calls into other modules.
1> lists:member(2, [1, 2, 3]).
true
2> string:uppercase("hello").
<<"HELLO">>
Import selectively
The import attribute brings a foreign function into your namespace so you can drop the module prefix. Import one function at a time, by name and arity.
Most style guides skip imports: the module prefix shows where a function lives, and the reader thanks you.
-import(lists, [member/2, seq/2]).
1> member(2, [1, 2, 3]).
true
Where modules live
The compiler looks for module_name.erl, compiles it to module_name.beam, and loads the beam file at runtime. The source file name and the module name are the same string.
The code server keeps all loaded modules in one table, which lesson 44 explores with code:which and friends.
Next: Funs: anonymous functions
Article author: Arthur Isaev