I'm learning Haskell, and I wrote a simple Fibonacci function:
fib :: Int -> Int
fib 1 = 1
fib 0 = 0
fib n = (fib (n-1)) + (fib (n-2))
It seems to compile ok, and loading this script into the GHCI REPL I could mess around with a few numbers. I tried
fib 33
and was surprised that it took about 4 seconds to give the result. (Sorry I don't know how to time a function in Haskell yet, so counted myself).
Fib 33 isn't particularly taxing. The answer is less than 4 million. So I'm assuming my code is not very well written or there is some issue with the way I am doing recursion perhaps (well, it isn't well written in that it doesn't take into account negative integers). The question is, why is it slow? Any help appreciated.
fib(5)
is calculated. Every iteration, you calculate all "inner" fibonacci numbers again. – WeStfibs = 0 : 1 : zipWith (+) fibs (tail fibs)
withfib n = fibs!!n
. See the haskell wiki about the Fibonacci sequence. It's amusing that Fibonacci is famous for this sequence, which was just a little exercise in the book he should be famous for, which introduced place value to Western Europe. – AndrewC