Fibonacci Haskell 实现的问题
刚刚开始重新学习 Haskell(在大学学过,但忘记了大部分内容),我想我会首先实现一个斐波那契函数。然而,即使对于非常小的n
,我仍然会遇到堆栈溢出。
谁能发现我的功能有什么问题吗?
fib :: Integer -> Integer
fib 0 = 0
fib 1 = 1
fib n = fib (n-1) + fib (n+1)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的斐波那契公式中有一个错误:
请注意最后一项,其中有
n-2
而不是n+1
。You have an error in your fibonacci formula:
Note the very last term where there is
n-2
instead ofn+1
.这是一个非常糟糕的实现,你应该使用尾递归,从 0 或 1 开始向上并传递前两个斐波那契数。还有一个错误,fib n 取决于 fib n+1。
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.