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
  •  | 
  •  

문제

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?

도움이 되었습니까?

해결책

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).

다른 팁

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.:)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top