In Coconut
Here’s the code for defining an infinite list representing the Fibonacci series in Coconut:
def fib() = (0, 1) :: map ((+), fib(), fib()$[1:])
Let’s break down this code, step-by-step to understand what exactly is going here. First, we defined our first two Fibonacci numbers to be
(0,1)
and we used the ::
operator to concatenate the rest of the Fibonacci sequence. We use a higher order function map, by applying the (+)
arithmetic operator in fib()
and the rest of the elements fib()$[1:]
Obtaining the
nth
element is straightforward. Try finding the 20th element.
Show Solution:
In the next section, we'll take a look at implementing a factorial function.