Skip to content

Instantly share code, notes, and snippets.

@jarrodhroberson
Created February 14, 2014 03:22
Show Gist options
  • Save jarrodhroberson/8995256 to your computer and use it in GitHub Desktop.
Save jarrodhroberson/8995256 to your computer and use it in GitHub Desktop.
Counters In Erlang
-module(counter).
-export([inc/1,inc/2,dec/1,dec/2,current/1,reset/1,start/1,loop/1]).
start(Name) ->
register(Name,spawn(counter,loop,[0])),
ok.
inc(Name, Amount) ->
Name ! {inc_counter, Amount},
current(Name).
inc(Name) ->
inc(Name, 1).
dec(Name, Amount) ->
Name ! {dec_counter, Amount},
current(Name).
dec(Name) ->
dec(Name, 1).
current(Name) ->
Name ! {get_counter, self()},
receive
{ counter_value, Count } ->
Count
end.
reset(Name) ->
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).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment