Sieve of Eratosthenes in Erlang PDF Print E-mail
Saturday, 04 April 2009 20:53

This is my first real attempt at a semi-useful program in Erlang.  It is the Sieve of Eratosthenes, which is a prime number generator.  The main function is primes() which accepts the number that you would like to count up to.  Luckly, Erlang is a Functional language, so I was able to do some fun things.

I had to modify the algorithm, as the original algorithm uses arrays, and arrays aren't really used in Erlang.  I suppose this is probably due to the functional roots that Erlang has.  Scheme in practice tends to stay away from vectors and uses lists more.  I decided to use lists in Erlang, and was able to do some nice recursion, as is normal with Scheme.

-module(sieve).
-export([primes/1]).

%% Removes the multiples of a number from a list
remove_multiples(_, []) -> [];
remove_multiples(N, [H|T]) when (H rem N == 0) ->
remove_multiples(N, T);
remove_multiples(N, [H|T]) ->
[H|remove_multiples(N, T)].

%% Generate primes by creating a list of numbers from 0 to N.
%% Then recurse through the list, eliminating multiples at each recursion.
primes(N) ->
primes(N, lists:seq(2,N)).
primes(N, [H|T]) ->
StopNumber = math:sqrt(N),
if
H < StopNumber
[H|primes(N,remove_multiples(H, T))]; %% Does this blow your mind?
true -> [H|T]
end.

I'm not experienced with Erlang yet, so my apologies if I have bad Erlang style.  I wanted to put N < math:sqrt(N) in the guard for the function, but apparantly, you can't put function results in guards, so I had to store it in the StopNumber variable, and use an if statement.

 

Book Wish List

StackOverflow