Generate a sequence of Fibonacci number in Scala [

2019-01-10 21:17发布

This question already has an answer here:


  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
  }

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?

7条回答
唯我独甜
2楼-- · 2019-01-10 21:58

This is a bit more elegant:

val fibs: Stream[Int] = 0 #:: fibs.scanLeft(1)(_ + _)

With Streams you "take" a number of values, which you can then turn into a List:

scala> fibs take 10 toList
res42: List[Int] = List(0, 1, 1, 2, 3, 5, 8, 13, 21, 34)

Update: I've written a blog post which goes more detail regarding how this solution works, and why you end up with a Fibonacci sequence!

查看更多
登录 后发表回答