[erlang-questions] first erlang program
Steve Davis
steven.charles.davis@REDACTED
Sat Jan 5 16:43:07 CET 2013
And... for fun... a refactored version that should scale and also avoid
io:format:
-module(eratos).
-export([primes/1]).
primes(Max) ->
ResultPid = self(),
Pid = spawn(fun() -> sieve(ResultPid) end),
map(Pid, 2, Max).
map(Pid, N, Max) when N =< Max ->
Pid ! N,
map(Pid, N + 1, Max);
map(Pid, _, _) ->
Pid ! done,
reduce([]).
reduce(Acc) ->
receive
done ->
lists:reverse(Acc);
Prime ->
reduce([Prime|Acc])
end.
sieve(ResultPid) ->
receive
done ->
ResultPid ! done;
Prime when is_integer(Prime) ->
ResultPid ! Prime,
Pid = spawn(fun() -> sieve(ResultPid) end),
sieve(Prime, Pid)
end.
sieve(Prime, Pid) ->
receive
done ->
Pid ! done;
N when N rem Prime =/= 0 ->
Pid ! N,
sieve(Prime, Pid);
N when is_integer(N) ->
sieve(Prime, Pid)
end.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20130105/268e860f/attachment.htm>
More information about the erlang-questions
mailing list