Posted By

fuzzylollipop on 11/20/09


Tagged

erlang


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

fuzzylollipop


Counters in Erlang


 / Published in: Other
 

URL: http://www.vertigrated.com/blog/2009/11/counters-in-erlang/

  1. -module(counter).
  2.  
  3. -export([inc/1,inc/2,dec/1,dec/2,current/1,reset/1,start/1,loop/1]).
  4.  
  5. start(Name) ->
  6. register(list_to_atom(Name),spawn(counter,loop,[0])),
  7. ok.
  8.  
  9. inc(Name, Amount) ->
  10. list_to_atom(Name) ! {inc_counter, Amount},
  11. current(Name).
  12.  
  13. inc(Name) ->
  14. inc(Name, 1).
  15.  
  16. dec(Name, Amount) ->
  17. list_to_atom(Name) ! {dec_counter, Amount},
  18. current(list_to_atom(Name)).
  19.  
  20. dec(Name) ->
  21. dec(Name, 1).
  22.  
  23. current(Name) ->
  24. list_to_atom(Name) ! {get_counter, self()},
  25. receive
  26. { counter_value, Count } ->
  27. Count
  28. end.
  29.  
  30. reset(Name) ->
  31. list_to_atom(Name) ! reset,
  32. current(Name).
  33.  
  34. loop(Counter) ->
  35. receive
  36. {inc_counter, Amount} ->
  37. NewCounter = Counter + Amount;
  38. {dec_counter, Amount} ->
  39. NewCounter = Counter - Amount;
  40.  
  41. {get_counter, Pid} ->
  42. Pid ! { counter_value, Counter },
  43. NewCounter = Counter;
  44. reset ->
  45. NewCounter = 0
  46. end,
  47. loop(NewCounter).

Report this snippet  

You need to login to post a comment.