Learning functional programming using scala. Came across this exercise.
Write a recursive function to get the nth Fibonacci number (http://mng.bz/C29s). The first two Fibonacci numbers are 0 and 1. The nth number is always the sum of the previous two—the sequence begins 0, 1, 1, 2, 3, 5. Your definition should use a local tail-recursive function.
def fib(n: Int): Int
My answer computes n+1 values and returns the nth. Can anyone show me a better implementation where the extra n+1th value is not computed?
object patterns {
def fib(n : Int): Int = {
@annotation.tailrec
def go(n: Int, prev2: Int, prev: Int): Int =
if(n<=0) prev2
else go(n-1, prev, prev2+prev)
go(n, 0, 1)
}
}
In case anyone is interested, this is from the book functional programming in scala by Chiusano and Bjarnason. Exercise 2.1 Looking forward to the replies.