开发者

What does in ? operator/prefix in Erlang mean?

What does the question mark in ?MODULE (which can be seen in all generated code by Mochiweb make command) mean?

-export([start/1, stop/0, loop/2]).

start(Options) ->
    {DocRoot, Options1} = get_option(docroot, Options),
       Loop = fun (Req) ->
               ?MODULE:loop(Req, DocRoot)
       end,
    mochiweb_http:start([{name, ?MODULE}, {loop, Loop} | Options1]).

stop() ->
    mochiweb_http:stop(?MODULE).

loop(Req, DocRoot) -&g开发者_StackOverflowt;
    ...


It denotes a preprocessor macro. ?MODULE is one of the predefined macro constants that expand to current module's name.


Well this is the way we represent MACROS in Erlang. At compile time, these macros are replaced with the actual meanings. They save on re-writing pieces of code or on abstracting out a parameter you may change in future without changing your code (would only require a re-compilation of the source that depends on the MACRO).

Forexample:

-module(square_plus).
-compile(export_all).
-define(SQUARE(X),X * X).

add_to_square(This,Number)-> ?SQUARE(This) + Number.

Is the same as:

-module(square_plus).
-compile(export_all).

add_to_square(This,Number)-> (This * This) + Number.


-define(Macro,Replacement). is used by the preprocessor to supports macros to have more readable programs. It can be used to have a conditional compilation. It is recommended that If a macro is used in several modules, it's definition is placed in an include file.

A macro definition example:

-define(TIMEOUT, 200).

For using macro:

?TIMEOUT.

List of predefined macros:

?MODULE: The name of the current module.
?FILE: The file name of the current module.
?LINE: The current line number.
?MACHINE: The machine name.

Source: https://www.dcs.gla.ac.uk/~amirg/tutorial/erlang/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜