What are the two ways of maintaining state between tail-recursive instances of a function in Erlang?

StackOverflow https://stackoverflow.com/questions/23200668

  •  07-07-2023
  •  | 
  •  

Question

The equivalent in a procedural language (e.g. in Java) would be local variables (or instance variables) declared outside of a loop whose contents use and update them. How can I do that in Erlang?

Was it helpful?

Solution

You pass the state as parameters in the recursive call. Example loop that receives N Msgs and returns them as a list:

loop(N) ->
  loop(N, 0, []).

loop(N, Count, Msgs) when Count < N ->
   receive
      Msg -> loop(N, Count+1, [Msg|Msgs])
   end;
loop(_, _, Msgs)
    list:reverse(Msgs).

OTHER TIPS

I hope it wasn't homework question but I'm confused with "two ways" in subject.

The most proper way, of course, is to extend recursive function definition with at least one argument to carry all needed data. But, if you can't use it, and you are sure only one instance of such recursive cycle will be in effect in a moment (or they will be properly stacked), and function invocations are in the same process, then process dictionary will help you. See put() and get() in erlang module, and invent unique terms to be used as keys. But this is definitely a kind of hack.

One could invent more hacks but all them will be ugly.:)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top