In Python
Let's start with the basics: writing a Fibonacci program that calculates the nth Fibonacci number using simple recursion in Python.
def fib1(n):
if n == 0:
return 0
elif n == 1:
return 1
else :
return fib1(n-2) + fib1(n-1)
fib1(20) #returns 6765
Since Python does not have lazy evaluation, what this is really doing is calculating every Fibonacci number up until n. A very inefficient approach to the Fibonacci numbers!
Another approach to generating Fibonacci numbers involves creating an infinite lists of iterators. In Python, we can write a generator to do this:
def fib2():
a, b = 0, 1
while 1:
yield a
a, b = b, a + b
next(itertools.islice( fib2(), 20, None)) #returns 6765
next(itertools.islice( fib(), n, None))
which requires the itertools library, and is not quite elegant.
In the next section, let's explore how Coconut can simplify our approach to the Fibonacci sequence.