[erlang-questions] How to do counters?

Jarrod Roberson jarrod@REDACTED
Mon Jun 29 22:02:42 CEST 2009


On Mon, Jun 29, 2009 at 1:18 PM, Jarrod Roberson <jarrod@REDACTED>wrote:

> 2009/6/29 Witold Baryluk <baryluk@REDACTED>
>
>>
>> Another way is using just presented examples, and registering them on
>> different names, or not registering them at all (they will be only
>> referenced by Pid returned from spawn).
>>
>> You can register it using something like that:
>>
>> start(X) ->
>>  Pid = spawn(counter,loop,[0]),
>>  Name = list_to_atom("counter_"++X),
>>  register(Name, Pid),
>>  ok.
>
>
> actually this is what I was trying to accomplish my self, I just couldn't
> figure how how.
>
> I guess I need to send in the name in the inc, dec, current methods as well
> then?
>

so this is what have so far, is this the best "erlangy" way of doing this?

-module(counter).

-export([inc/1,inc/2,dec/1,dec/2,current/1,reset/1,start/1,loop/1]).

start(Name) ->
   register(list_to_atom(Name),spawn(counter,loop,[0])),
   ok.

inc(Name, Amount) ->
    list_to_atom(Name) ! {inc_counter, Amount},
    current(Name).

inc(Name) ->
   inc(Name, 1).

dec(Name, Amount) ->
    list_to_atom(Name) ! {dec_counter, Amount},
    current(list_to_atom(Name)).

dec(Name) ->
   dec(Name, 1).

current(Name) ->
   list_to_atom(Name) ! {get_counter, self()},
   receive
       { counter_value, Count } ->
           Count
   end.

reset(Name) ->
    list_to_atom(Name) ! reset,
    current(Name).

loop(Counter) ->
   receive
       {inc_counter, Amount} ->
           NewCounter = Counter + Amount;
       {dec_counter, Amount} ->
           NewCounter = Counter - Amount;
       {get_counter, Pid} ->
           Pid ! { counter_value, Counter },
           NewCounter = Counter;
       reset ->
           NewCounter = 0
   end,
   loop(NewCounter).


More information about the erlang-questions mailing list