Problem 2 is again stated simply- “Find the sum of all the even-valued terms in the (Fibonacci) sequence which do not exceed four million.”
The Fibonacci Sequence is the sequence which runs 1, 2, 3, 5, 8, 13, 21 etc. in which each term is the sum of the previous two terms.
Again, conceptually easy. Just run the terms until one exceeds 4,000,000 and sum those which are divisible by 2.
In a procedural language, this is another problem that I can solve as fast as I can type. It’s very straight-forward in approach.
But I’ve quickly learned that recursion is the default thought-process for the functional language Erlang, so I immediately set about trying to think of the problem recursively. I admit to heading down a couple of dead end paths at first, really just approaching it from the wrong end. I kept worrying about building the terms when what I really wanted to do was focus on accumulating the sum. Once I realized that, everything fell into place quickly. The end result is a little messy, having to call the function with seed values – sumofevenfib(1,1,0) and having the cutoff value of 4,000,000 hardcoded. But it works.
Only a couple of problems into the euler series, but I’m getting the effects I wanted. Spending a lot more time studying up on Erlang, reading about why it’s designed the way it is, and understanding what the syntax is really saying and so on. Also learning to move from the procedural-by-reflex mindset I’ve developed over years and years of coding to a more functional approach. There’s definitely a switch I need to flip over in my head about that kind of thing.
Le code -
-module(euler2).
-export([sumofevenfib/3]).
sumofevenfib(Prev,Cur,Sum) ->
Next = Prev + Cur,
if
Next =< 4000000 ->
if
Next rem 2 == 0 ->
sumofevenfib(Cur,Next,Sum+Next);
true ->
sumofevenfib(Cur,Next,Sum)
end;
true -> Sum
end.

Post a Comment