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.
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 withReplacement
.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With