Erlang Programming/Quick tips

From Wikibooks, open books for an open world
Jump to navigation Jump to search

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:


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


You can manually 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},
     {Dest, Answer} -> Answer
   after 1000 ->
     {Dest, did_not_answer_msg, Msg}

This helps keep synchronous commands between processes from getting answers from the wrong process. We force the identification of the process providing the answer, and sequential queuing should handle the rest.