[erlang-questions] Newbie Erlang programmer looking for feedback! :)

JohnyTex <>
Tue Mar 29 10:33:37 CEST 2011

Hello everybody! I'm new to Erlang and pretty new to functional
programming in general. I've been having a really good time with
Erlang so far (even though Erlang's punctuation has had me trip up a
few times ;)), but I'd really love it if I could get some feedback on
my code from more experienced Erlang programmers. My code seems to
work alright, but I'm sure you guys could offer a lot of advice for
improvement! :)

Anyway, here's my solution to the second problem from Project Euler
(http://projecteuler.net/index.php?section=problems&id=2). The problem
is to find the sum of all the even fibonacci numbers below four
million; I thought this could be a good exercise since it would let me
try my hand at implementing lazy sequences and working with lists.

I split up the program into two modules. The first one is for handling
lazy sequences, since I thought that would be a good way to find our
list of primes:

-export([takewhile/2, take/2]).

%% Recursively pick elements from a lazy sequence while Pred(H) is
takewhile(Pred, [H|T]) ->
    case Pred(H) of
        true -> [H|takewhile(Pred, T())];
        false -> []

%% Take a certain number of elements from a lazy sequence
%% A non-tail recursive version
take(0, _) -> [];
take(Number, [H|T]) ->
    [H|take(Number - 1, T())].

The second module actually solves the problem:

-import(seqs, [takewhile/2]).
-export([lazyfib/0, solve/0]).

%% Sums the numbers in a list (for practice's sake)
sum([]) -> 0;
sum([H|T]) -> H + sum(T).

%% Practicing some list comprehensions as well!
filter(P, Xs) -> [ X || X <- Xs, P(X) ].

%% Lazy sequence that generates fibonacci numbers
lazyfib(A, B) -> [A | fun () -> lazyfib(B, A + B) end].
lazyfib() -> lazyfib(0, 1).

%% Generate all fibonacci terms that are less than 4 million and sum
%% even terms
solve() ->
    Fibs = seqs:takewhile(fun (X) -> X < 4000000 end, lazyfib()),
    sum(filter(fun (X) -> X rem 2 =:= 0 end, Fibs)).

Thanks in advance, and please tell me if this is not the appropriate
forum for this kind of question! :)

More information about the erlang-questions mailing list