Problem with Fibonacci Haskell Implementation

邮差的信 提交于 2019-12-25 01:34:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!