Wrote my first erlang program -- sieve of eratostenes;<br>--------------------------------------------<br>-module(eratos).<br>-export([main/0, gen/1, sieve/0, filtloop/2]).<br><br>-define (MAX, 200000).<br>gen(Proc) -> gen(Proc,2).<br>
gen(Proc, N) -><br> if N =< ?MAX -> Proc ! N,<br> gen(Proc, N+1);<br> true -> stop<br> end. <br><br>filtloop(Prime, NS) -> % NS is NextSieve<br> receive<br> N when is_integer(N) -><br>
if N rem Prime =/= 0 -> <br> NS ! N;<br> true -> ok<br> end,<br> filtloop(Prime,NS);<br> stop -> ok; % io:format("Stopping ~w~n", [Prime]);<br> XX -> io:format("Something strange in filtloop~w~n", [XX])<br>
end.<br><br>sieve() -><br> receive Prime -> ok end,<br> io:format("~w~n", [Prime]),<br> Nextsieve = spawn(fun sieve/0),<br> filtloop(Prime, Nextsieve).<br><br>main() -><br> gen(spawn (fun sieve/0)).<br>
------------------------------<br clear="all"><br><br>It is modelled after this shell script (consisting of 3 scripts)<br><br>$ cat gen.sh<br>i=2<br>while true; do<br> echo $i<br> i=`expr $i + 1`<br>done<br>--------<br>
$ cat filt.sh <br>while true; do<br> read x<br> if [ 0 != `expr $x % $1` ] ; then<br> echo $x<br> fi<br>done<br>-------------<br>$ cat sieve.sh <br>read x<br>echo $x<br>filt.sh $x | sieve.sh<br>----------------<br>
Call like this<br>gen.sh | sieve<br><br>Performance wise its fun to watch the erlang go 10 (50?) times faster than the shell script<br>However the shell script has an elegance that the erlang does not have because I dont know how to 'anonymize'<br>
the stdin/stdout that a classic Unix pipeline gives<br><br>Also more basic noob questions like how to avoid the io:format statements etc<br><br>TIA for any tips/guidance<br>Rusi<br>-- <br><a href="http://www.the-magus.in" target="_blank">http://www.the-magus.in</a><br>
<a href="http://blog.languager.org" target="_blank">http://blog.languager.org</a><br><br>