[erlang-questions] first erlang program

Rustom Mody rustompmody@REDACTED
Fri Jan 4 18:19:54 CET 2013


Wrote my first erlang program -- sieve of eratostenes;
--------------------------------------------
-module(eratos).
-export([main/0, gen/1, sieve/0, filtloop/2]).

-define (MAX, 200000).
gen(Proc) -> gen(Proc,2).
gen(Proc, N) ->
    if N =< ?MAX -> Proc ! N,
           gen(Proc, N+1);
       true     ->  stop
    end.

filtloop(Prime, NS) -> % NS is NextSieve
    receive
    N when is_integer(N) ->
        if N rem Prime =/= 0 ->
            NS ! N;
           true          -> ok
        end,
        filtloop(Prime,NS);
    stop -> ok; % io:format("Stopping ~w~n", [Prime]);
    XX -> io:format("Something strange in filtloop~w~n", [XX])
     end.

sieve() ->
    receive Prime -> ok end,
    io:format("~w~n", [Prime]),
    Nextsieve = spawn(fun sieve/0),
    filtloop(Prime, Nextsieve).

main() ->
    gen(spawn (fun sieve/0)).
------------------------------


It is modelled after this shell script (consisting of 3 scripts)

$ cat gen.sh
i=2
while true; do
    echo $i
    i=`expr $i + 1`
done
--------
$ cat filt.sh
while true; do
  read x
  if [ 0 != `expr $x % $1` ] ; then
     echo $x
  fi
done
-------------
$ cat sieve.sh
read x
echo $x
filt.sh $x | sieve.sh
----------------
Call like this
gen.sh | sieve

Performance wise its fun to watch the erlang go 10 (50?) times faster than
the shell script
However the shell script has an elegance that the erlang does not have
because I dont know how to 'anonymize'
 the stdin/stdout that a classic Unix pipeline gives

Also more basic noob questions like how to avoid the io:format statements
etc

TIA for any tips/guidance
Rusi
-- 
http://www.the-magus.in
http://blog.languager.org
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20130104/7c24282d/attachment.htm>


More information about the erlang-questions mailing list