Concurrent programming in Erlang

2.4. The Module System

Erlang has a module system which allows us to divide a large program into a set of modules. Each module has its own name space; thus we are free to use the same function names in several different modules, without any confusion.

The module system works by limiting the visibility of the functions contained within a given module. The way in which a function can be called depends upon the name of the module, the name of the function and whether the function name occurs in an import or export declaration in the module.

-module(lists1).
-export([reverse/1]).

reverse(L) ->
        reverse(L, []).

reverse([H|T], L) ->
        reverse(T, [H|L]);
reverse([], L) ->
        L.

This program defines a function reverse/1 which reverses the order of the elements of a list. reverse/1 is the only function which can be called from outside the module. The only functions which can be called from outside a module must be contained in the export declarations for the module.

The other function defined in the module, reverse/2, is only available for use inside the module. Note that reverse/1 and reverse/2 are completely different functions. In Erlang two functions with the same name but different numbers of arguments are totally different functions.

2.4.1. Inter-module calls

There are two methods for calling functions in another module:

-module(sort1).
-export([reverse_sort/1, sort/1]).

reverse_sort(L) ->
        lists1:reverse(sort(L)).

sort(L) ->
        lists:sort(L).

The function reverse/1 was called by using the fully qualified function name lists1:reverse(L) in the call.

You can also use an implicitly qualified function name by making use of an import declaration, as in Program 2.4.

-module(sort2).
-import(lists1, [reverse/1]).

-export([reverse_sort/1, sort/1]).

reverse_sort(L) ->
        reverse(sort(L)).

sort(L) ->
        lists:sort(L).

The use of both forms is needed to resolve ambiguities. For example, when two different modules export the same function, explicitly qualified function names must be used.