csp sieves in erlang
Rob pike's sieve algorithm in erlang
If anyone watched Rob Pike's demo of newsqueak and csp style programming, he could see a very pretty distributable algorithm for calculating prime numbers, well, i've managed to "translate" it to erlang, so here is the code:
-module(sieve3).
-export([start/0, start/1]).
counter(start, none, Max) ->
FilterPid = spawn(fun() -> filter(2, none) end ),
FilterPid ! 1,
counter(2, FilterPid, Max);
counter(N, FilterPid, Max) ->
FilterPid ! {num, N},
if
N == Max ->
FilterPid ! term;
true ->
counter(N+1, FilterPid, Max)
end.
filter(N, none) ->
receive
{num, M} when M rem N =:= 0 ->
filter(N, none);
{num, M} ->
ChildPid = spawn(fun() -> filter(M, none) end),
io:format("~B ", [M]),
filter(N, ChildPid);
term ->
false
end;
filter(N, ChildPid) ->
receive
{num, M} when M rem N =:= 0 ->
filter(N, ChildPid);
{num, M} ->
ChildPid ! {num, M},
filter(N, ChildPid);
term ->
ChildPid ! term
end.
start(Max) ->
io:format("Starting counter...~n"),
counter(start, none, Max),
io:format("Done~n").
start() ->
io:format("Starting counter...~n"),
counter(start, none, 100),
io:format("Done~n").
I'm happy!
Cheers!
