在 Scala 中编写斐波那契函数的最快方法是什么? [英] What is the fastest way to write Fibonacci function in Scala?

查看:22
本文介绍了在 Scala 中编写斐波那契函数的最快方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从 非常简单,到更复杂的.

我不完全确定哪个是最快的.我倾向于使用 memoization 的印象更快,但是我想知道为什么 Scala 没有本地 memoization.

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 构建任何元组对象,并且在语法上很容易理解.

This doesn't need to build any Tuple objects for the zip and is easy to understand syntactically.

这篇关于在 Scala 中编写斐波那契函数的最快方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆