Erlang (programming language)/Tutorials/Quick tips

From Citizendium
Jump to navigation Jump to search

Quick tips

Quick tips for faster programming.

One thing that can slow you down when you are getting started or trying to do some rapid prototyping is to export functions all the time. Rather, you can use the compiler directive. This makes programming erlang much more enjoyable, not to have to manually type:

 export(function_not_an_other_one/4).

every-time you add a function and would like to test it. Rather, you can use:

 compile(export_all).

You can manyally export only the things you need to when you are done with the program.

Another handy trick is to use

 42> make:all([load]). 

Rather than compile the latest version all the time.

 43> c(my_module_v17).

or is it

 44> c(my_module_v18).

?Module in code gives the current module name, which is super helpful when spawning.

 spawn(?Module, fun_name, arity),

Otherwise, you need to change the module name in every spawn every time you change the name of the module. If you would like to keep an eye on a process you can monitor it, after you have registered it.

 45> register(my_loop, spawn(my_module, my_loop, [])).
 46> Mon_my_loop = erlang:monitor(process, my_loop).

A helpful utility function is rpc.

 rpc(Dest, Msg) ->
   To ! {self(), Msg},
   receive
     {Dest, Answer} -> Answer
   after 1000 ->
     {Dest, did_not_answer, Msg}
   end.

This helps keep synchronous commands between processes from getting answers from the wrong process. See - ITERATOR - for an example using rpc. A way to make sure rpc gets the right answer is to use a unique id number. We generate a unique id with erlang:make_ref(), then use it when we return the answer.

 rpc(Dest, Msg) ->
   Ref = erlang:make_ref(),
   To ! {self(), Ref, Msg},
   receive
     {Dest, Ref, Answer} -> Answer
   after 1000 ->
     {Dest, did_not_answer, Msg}
   end.

Nothing could possibly go wrong except if the answering process has expired before answering.

If you wish to work with a standard rpc, try

 rpc:call(Node, Module, Function, Args)

using the local node() at both ends.