How to make this fibonacci function faster?

Viewed 2152

This function to find the nth fibonacci works.

a = 1
b = 2

fibonacci :: Int -> Int
fibonacci 1 = a
fibonacci 2 = b
fibonacci n = (fibonacci (n-1)) + (fibonacci (n-2))

But it is slow. If I do map fibonacci [1..] it really slows down as the numbers come. I'm guessing this is overhead due to how much stack is being used and the sheer number of calculations - doing each one down to a and b rather than just adding the last two together.

How can I improve it so it's much faster, but still use a functional programming style? (I'm a definite haskell and FP newbie!) I tried something in Python that was lightning by comparison.

Tips are as welcome if not more welcome than working code!

3 Answers
Related