I love learning and checking out stuff.
Today, the geek in me has, once again, been satisfied. Sort of. To culminate my Erlang adventure which I started today, I decided to do a simple exercise: the classic Fibonacci sequence. The function interface is simple: fibo(x, y, n), where x and y are the first to elements of the sequence, and n is the number of elements in the sequence and assumed to be at least two-- the first two elements, and in the true Fibonacci sequence, x is 0 and y is 1.
For example, fibo(1, 20, 4) will yield [1, 20, 21, 41] and fibo(0, 1, 8) will yield [0, 1, 1, 2, 3, 5, 8, 13].
Here's my solution:
-module(fibo).
-export([fibo/3]).
fibo(_, _, 0) -> [];
fibo(X, Y, N) -> [X|fibo(Y, X+Y, N-1)].
I'm an Erlang newbie and I'm finding it difficult to think in Erlang. Recursions, recursions! Yum! But it's always cool to learn "new" ways of looking at problems.
And I also implemented a non-recursive solution in Python:
def fibo(x, y, n):
res = [x, y]
zo = y
z = x + zo
for i in range(n-2):
res.append(z)
z, zo = zo + z, z
return res