Search code examples
haskellstack-overflowfibonacci

Problem with Fibonacci Haskell Implementation


Just started re-learning Haskell (did it at uni but forgot most of it) and thought I would implement a Fibonacci function to start of with. However, I keep getting a stackoverflow, even for very small n.

Can anyone spot any problems with my function?

fib :: Integer -> Integer
fib 0 = 0
fib 1 = 1
fib n = fib (n-1) + fib (n+1)

Solution

  • You have an error in your fibonacci formula:

    fib :: Integer -> Integer
    fib 0 = 0
    fib 1 = 1
    fib n = fib (n-1) + fib (n-2)
    

    Note the very last term where there is n-2 instead of n+1.