[erlang-questions] How to do counters?

Alin Popa alin.popa@REDACTED
Fri Jun 26 07:28:26 CEST 2009


Hi Jarrod,

Here is an example which might help:

*-module(test_counter).
-export([loop/0, increment_counter/2]).

loop() ->
    loop(0).

loop(CurrentCounter) ->
    receive
        {Pid, inc, Counter} ->
            NewCounter = inc(Counter, CurrentCounter),
            io:format("New counter ~p~n",[NewCounter]),
            Pid ! {NewCounter},
            loop(NewCounter);
        _ ->
            loop(CurrentCounter)
    end.

inc(Counter, NewValue) ->
    Counter + NewValue.

increment_counter(Pid, Count) ->
    Pid ! {self(), inc, Count},
    receive
        {NewValue} ->
            io:format("Got ~p~n", [NewValue]);
        _ ->
            ok
    end.

*
On Fri, Jun 26, 2009 at 4:45 AM, Jarrod Roberson <jarrod@REDACTED>wrote:

> On Thu, Jun 25, 2009 at 7:10 PM, Vance Shipley <vances@REDACTED> wrote:
>
> > On Thu, Jun 25, 2009 at 06:29:26PM -0400, Jarrod Roberson wrote:
> > }  what do you mean by "internal state" I don't understand how a process
> > would
> > }  store any mutable state
> >
> > http://erlang.org/doc/man/gen_server.html#Module:handle_call-3
> >
> > The last argument in gen_server/gen_fsm callback functions
> > is State.  It's "mutable" by the fact that the return value
> > includes NewState.
> >
> > In functional programming everything a function needs to know
> > is passed in as arguments.  Tail recursion keeps the balls in
> > the air.
> >
> >        loop(State) ->
> >                ...
> >                loop(NewState).
> >
> >
> > --
> >         -Vance
> >
>
> I still don't see how this is supposed to work.
> If I do tail recursion, how do I return anything, if the loop(NewState)
> needs to be the last thing I do?
>
> If I have functions inc() dec() and current() which should return the
> current value of the counter, how do all these functions share state? I
> can't have the client pass in the state because I will have many client
> processes calling the counter functions.
>
> There seems to be something I am missing that you guys know and I don't.
>



-- 
Regards,

Alin


More information about the erlang-questions mailing list