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

Macros

Macros allow you to write abbreviations of Erlang constructs that the Erlang Preprocessor (EPP) expands at compile time. You can use macros to make programs more readable and to implement features outside the language itself. With conditional macros, it becomes possible to write programs that can be customized in different ways, switching between debugging and production modes or among different architectures.

Simple Macros

The simplest macro can be used to define a constant, as in:

-define(TIMEOUT, 1000).

The macro is used by putting a ? in front of the macro name, as in:

receive
    after ?TIMEOUT -> ok
end

After macro expansion in epp, the preceding code will give the following Erlang program:

receive
    after 1000 -> ok
end

The general form of a simple macro definition is:

-define(Name,Replacement).

where it is customary—but not required—to CAPITALIZE the Name. In the earlier example, the Replacement was the literal 1000; it can, in fact, be any sequence of Erlang tokens—that is, a sequence of “words” such as variables, atoms, symbols, or punctuation. The result need not be a complete Erlang expression or a top-level form (i.e., a function definition or compiler directive). It is not possible to build new tokens through macro expansion. As an example, consider the following:

-define(FUNC,X).
-define(TION,+X).

double(X) -> ?FUNC?TION.

Here, you can see that the replacement for TION is not an expression, but on expansion a legitimate function (or top-level form) definition is produced. Note ...

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