Ted Karmel
Ted Karmel

Reputation: 1056

Erlang: What does question mark syntax mean?

What does the question mark in Erlang syntax mean?

For example:

Json = ?record_to_json(artist, Artist).

The full context of the source can be found here.

Upvotes: 26

Views: 7120

Answers (3)

Mohan
Mohan

Reputation: 157

? indicates Macros.

Erlang has predefined macros as well. Example: ?MODULE. You can find the complete list in https://www.erlang.org/doc/reference_manual/macros.html#predefined-macros

Upvotes: 0

Manoj Govindan
Manoj Govindan

Reputation: 74675

Erlang uses question mark to identify macros. For e.g. consider the below code:

-ifdef(debug).
-define(DEBUG(Format, Args), io:format(Format, Args)).
-else.
-define(DEBUG(Format, Args), void).
-endif.

As the documentation says,

Macros are expanded during compilation. A simple macro ?Const will be replaced with Replacement.

This snippet defines a macro called DEBUG that is replaced with a call to print a string if debug is set at compile time. The macro is then used in the following code thus:

?DEBUG("Creating ~p for N = ~p~n", [First, N]),

This statement is expanded and replaced with the appropriate contents if debug is set. Therefore you get to see debug messages only if debug is set.

Update

Thanks to @rvirding:

A question mark means to try and expand what follows as a macro call. There is nothing prohibiting using the macro name (atom or variable) as a normal atom or variable. So in [the above] example you could use DEBUG as a normal variable just as long as you don't prefix it with ?. Confusing, most definitely, but not illegal.

Upvotes: 31

Jon Skeet
Jon Skeet

Reputation: 1499870

Based on this documentation, I believe it's the syntax for referring to a macro.

And from Learn You Some Erlang:

Erlang macros are really similar to C's '#define' statements, mainly used to define short functions and constants. They are simple expressions represented by text that will be replaced before the code is compiled for the VM. Such macros are mainly useful to avoid having magic values floating around your modules. A macro is defined as a module attribute of the form: -define(MACRO, some_value). and is used as ?MACRO inside any function defined in the module. A 'function' macro could be written as -define(sub(X,Y), X-Y). and used like ?sub(23,47), later replaced by 23-47 by the compiler. Some people will use more complex macros, but the basic syntax stays the same.

Upvotes: 5

Related Questions