[erlang-questions] first erlang program

Steve Davis <>
Sat Jan 5 00:59:22 CET 2013


Hi Rusi,

Run that program two or three times in one vm session. You may find that 
io:format isn't the big issue here :-)

The io statements are simply a user echo (i.e. io:format(user, _, _)) A 
useful program would return the composite list... (think map/reduce).

Welcome to the fun - your first program is definitely more sophisticated 
than my first erlang program was.

Best,
Steve

On Friday, January 4, 2013 11:19:54 AM UTC-6, rusi wrote:
>
> 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/783fb94b/attachment.html>


More information about the erlang-questions mailing list