Paste number 45190: sieve

Paste number 45190: sieve
Pasted by: khigia
When:3 years, 3 days ago
Share:Tweet this! | http://paste.lisp.org/+YVA
Channel:None
Paste contents:
Raw Source | XML | Display As
-module(sieve).

-compile(export_all).

prime(N, Next, Client) ->
    receive
        N ->
            Client ! N,
            prime(N, Next, Client);
        X when is_integer(X) ->
            case X rem N of
                0 ->
                    prime(N, Next, Client);
                _ ->
                    NewNext = case Next of
                        undefined ->
                            spawn(?MODULE, prime, [N+1, undefined, Client]);
                        Pid ->
                            Pid
                    end,
                    NewNext ! X,
                    prime(N, NewNext, Client)
            end;
        Arg when is_pid(Next) ->
            % needed to be sure all message queue are processed
            Next ! Arg;
        Arg ->
            Client ! Arg
    end.

accumulator(Client, Acc) ->
    receive
        X when is_integer(X) ->
            %io:format("~w~n", [X]),
            accumulator(Client, [X|Acc]);
        _ ->
            Client ! lists:reverse(Acc)
    end.

start(N) when is_integer(N), N >= 2 ->
    Client = spawn(?MODULE, accumulator, [self(), []]),
    Primer = spawn(?MODULE, prime, [2, undefined, Client]),
    lists:foreach(fun(X) -> Primer ! X end, lists:seq(2, N) ++ [done]),
    receive
        Result ->
            Result
    end.

This paste has no annotations.

Colorize as:
Show Line Numbers

Lisppaste pastes can be made by anyone at any time. Imagine a fearsomely comprehensive disclaimer of liability. Now fear, comprehensively.