问题
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)
回答1:
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
.
回答2:
It's a very bad implementation, you should use tail recursion, start from 0 or 1 going upwards and passing the previous two fibonacci numbers. Also there is a bug, fib n depends on fib n+1.
fib :: Integer -> Integer
fib 0 = 0
fib n = iter 0 1 n
where iter :: Integer -> Integer -> Integer -> Integer
iter f1 f2 0 = f2
iter f1 f2 n = iter f2 (f1+f2) (n-1)
来源:https://stackoverflow.com/questions/6562387/problem-with-fibonacci-haskell-implementation