本文介绍了斐波那契哈斯克尔实现的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
刚开始重新学习Haskell(在uni上做过,但忘记了大部分),并且认为我会实现一个Fibonacci函数来开始。然而,我仍然得到一个stackoverflow,即使对于很小的 n 。任何人都可以发现我的函数有任何问题?
fib :: Integer - >整数
fib 0 = 0
fib 1 = 1
fib n = fib(n-1)+ fib(n + 1)
pre
解决方案您在斐波纳契公式中有错误:
fib :: Integer - >整数
fib 0 = 0
fib 1 = 1
fib n = fib(n-1)+ fib(n-2)
pre>
请注意最后一个有 n-2 而不是 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)解决方案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.
这篇关于斐波那契哈斯克尔实现的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!