18 November 2014

More Erlang!

Ok back at Erlang again, and this time we are on Problem two of Project Eular.

SPOILER ALERT! This is the question but not the answer.

Problem 2

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, …

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.


So this program was written by me typing fib(N) -> and staring at VIM for about 30min, getting distracted by HN, then sitting some more. It is such a simple problem and in Python I would have been done, but I needed time to get my head around an erlish way doing it.

Then it just appeared, and once the sytax errors were fixed it “Just Worked”. The first try. Scary suff I tell you…


fib(0) -> fib(0, 1, 0, []);
fib(Max) -> fib(1, 1, Max, []).

% As long as B is less than Max, keep accumulating.
fib(A, B, Max, Acc) when B < Max ->
    fib(B, A+B, Max, [B|Acc]);
fib(_, _, _, Acc) ->

And to test it out:

38> c(eular).
39> eular:fib(8).
40> eular:fib(0).
41> eular:fib(1).
42> eular:fib(2).
43> eular:fib(3).
44> eular:fib(10).

All is good in the world! Now we need a way to filter out the even numbers and I am sure the is a built in function for that.

Boom, there is(sorta)!

47> eular:fib(100).
48> lists:filter(fun(X) -> X rem 2 == 0 end, eular:fib(100)).

Now we need to sum them up!

49> lists:sum(lists:filter(fun(X) -> X rem 2 == 0 end, eular:fib(100))).

This is all good and stuff. Shall we take it to 11?

50> lists:sum(lists:filter(fun(X) -> X rem 2 == 0 end, eular:fib(4000000))).
<get a job you lazy hippy!>

Until next time… Take care of yourselves, and each other.