Process dictionary or cycle parameters?

When should I use the dictionary for the whole process and when should the state of the process be in the parameters of the loop function?

It:

loop() ->
  receive
     {From, subscribe} ->
       put(listeners, [From|get(listeners)]),
       ?MODULE:loop()
  end.

Or that:

loop(Listeners) ->
  receive
    {From, subscribe} ->
       ?MODULE:loop([From|Listeners])
  end.

?

The parameters of the loop function have the advantage that they cannot change the parameters anything (unless you make a strange magical bounce on another function, for example, a trampoline), but the state tends to add up, and the parameters with them.

How about dict as a parameter? The best of both worlds or the worst of both worlds?

+3
source share
3 answers

. , - , , - . Dict , "" , .

-record(state, {
           listeners = [],
           new_var   = undefined,
           new_var2  = ""
           ...
        }).

init() ->
  loop(#state{}).

loop(State) ->
  receive
    {From, subscribe} ->
       loop(State#state{listeners = [From|State#state.listeners]});
    somethingelse ->
       do_nothing(),
       loop(State)
  end.
+8

: -, .

, , "X" , Erlang.

, - , ? , : .

+2

Another big drawback of using a process dictionary is that it is much more difficult to trace when the data you have does not go through a function call.

+1
source

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


All Articles