在Scala中生成斐波那契数列 [英] Generate a sequence of Fibonacci number in Scala

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

问题描述



  def fibSeq(n: Int): List[Int] = {
    var ret = scala.collection.mutable.ListBuffer[Int](1, 2)
    while (ret(ret.length - 1) < n) {
      val temp = ret(ret.length - 1) + ret(ret.length - 2)
      if (temp >= n) {
        return ret.toList
      }
      ret += temp
    }
    ret.toList
  }

因此,以上是我的代码,该代码使用Scala将Fibonacci序列生成为值n.我想知道在Scala中是否有更优雅的方法可以做到这一点?

So the above is my code to generate a Fibonacci sequence using Scala to a value n. I am wondering if there is a more elegant way to do this in Scala?

推荐答案

定义斐波那契数列的方法有很多,但是我最喜欢的是这种方法:

There are many ways to define the Fibonacci sequence, but my favorite is this one:

val fibs:Stream[Int] = 0 #:: 1 #:: (fibs zip fibs.tail).map{ t => t._1 + t._2 }

这将创建一个流,当您需要特定的斐波那契数时,该流会被延迟评估.

This creates a stream that is evaluated lazily when you want a specific Fibonacci number.

首先,正如路易吉·普林格(Luigi Plinge)所指出的那样,一开始的懒惰"是不必要的. 其次,看看他的回答,他几乎只是在优雅地做同样的事情.

First, as Luigi Plinge pointed out, the "lazy" at the beginning was unnecessary. Second, go look at his answer, he pretty much did the same thing only more elegantly.

这篇关于在Scala中生成斐波那契数列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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