2011年8月23日 星期二

[Erlang] Prime generator

好久沒寫erlang, 有點生疏了~ 剛好看到有人在講prime generator, 就寫了一個~:P


-module(prime).

-export([generate_prime/1]).

filter_number(Pid, P) ->
receive
N when N rem P /= 0 ->
% In this case, the N can not be divided by P,
% so pass it to next prime process
Pid ! N;
_N -> ok
end,
filter_number(Pid, P).

prime() ->
Prime = receive P -> P end,
io:format("Prime ~p~n", [Prime]),
Pid = spawn(fun prime/0),
filter_number(Pid, P).

generate_prime(N) ->
% create the first prime process
Pid = spawn(fun prime/0),
lists:map(fun(X) -> Pid ! X end, lists:seq(2, N)),
ok.