What is the difference in functionality between these two blocks of code?

Firstly:

-module(some_mod). -compile(export_all). some_fun() -> fun f/0. f() -> ok. 

Secondly:

 -module(some_mod). -compile(export_all). some_fun() -> fun ?MODULE:f/0. f() -> ok. 

I discovered this change while updating the hot code. What is the difference between fun ?MODULE:f/0 and fun f/0 ?

+5
source share
2 answers

From Erlang Documentation :

  • The fun created by fun M:F/A is called external fun . When called, it always calls function F with arity A in the last code for module M Note that the M module does not even need to be loaded when fun fun M:F/A .

  • All other entertainment is called local entertainment . When local entertainment is called, the same version of the code that created the fun is called (even if a newer version of the module is loaded).

They have different ways of updating code, as the documentation says. The first module uses a local function ( fun f/0 ), and the second uses an external function ( fun ?MODULE:f/0 , which is replaced with fun some_mod:f/0 during preprocessing).

So, if you upgrade your first module (which uses a local function), processes using the some_fun function some_fun not use the newer version. But if you update the second module (which uses an external function), the latest version of the code will be called whenever some_fun is called from internal processes that were created even before the new version was downloaded.


Note: There can be only two versions of the module: old and new . If the third version of the module is loaded, the code server deletes (clears) the old code, and any processes lingering in it are terminated.

+7
source

?MODULE is a predefined macro that expands to the current module name. In your case, it will expand to some_mod . Referring to fun f/0 as fun ?MODULE:f/0 , a new version of f/0 will be used whenever a new compiled and downloaded version of some_mod .

+1
source

Source: https://habr.com/ru/post/1240406/


All Articles