在Scala中编写Fibonacci函数的最快方法是什么? [英] What is the fastest way to write Fibonacci function in Scala?
本文介绍了在Scala中编写Fibonacci函数的最快方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我从非常简单,我不确定哪一个是最快的.我倾向于这样一种印象,即使用备忘录的用户更快,但是我想知道为什么Scala没有本机的备忘录.
I'm not entirely sure which one is the fastest. I'm leaning towards the impression that the ones that uses memoization is faster, however I wonder why Scala doesn't have a native memoization.
有人能启发我以最好,最快(最简洁)的方式编写斐波那契函数的方法吗?
Can anyone enlighten me toward the best and fastest (and cleanest) way to write a fibonacci function?
推荐答案
对我来说,最简单的方法是定义一个递归内部尾函数:
for me the simplest defines a recursive inner tail function:
def fib: Stream[Long] = {
def tail(h: Long, n: Long): Stream[Long] = h #:: tail(n, h + n)
tail(0, 1)
}
这不需要为zip构建任何Tuple对象,并且在语法上易于理解.
This doesn't need to build any Tuple objects for the zip and is easy to understand syntactically.
这篇关于在Scala中编写Fibonacci函数的最快方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文