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?
I find this implementation to be more legible:
Here's yet another approach again using *Stream*s on an intermediary tuples:
My favorite version is:
With the default values you can just call
fibs()
and get the infiniteStream
.I also think it's highly readable despite being a one liner.
If you just want the first
n
then you can usetake
likefibs() take n
, and if you need it as a listfibs() take n toList
.Not as elegant as Streams, not lazy, but tailrecursive and handles BigInt (which is easy to do with Luigis scanLeft too, but not so with Tal's zip - maybe just for me).
There are many ways to define the Fibonacci sequence, but my favorite is this one:
This creates a stream that is evaluated lazily when you want a specific Fibonacci number.
EDIT: 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.