According to scala docs stream implements lazy lists where elements are only evaluated when they are needed. Example;
val fibs: Stream[BigInt] = BigInt(0) #:: BigInt(1) #:: fibs.zip(fibs.tail).map(n => {
n._1 + n._2
})
After that in scala repl;
fibs(4)
fibs
It will print out;
res1: Stream[BigInt] = Stream(0, 1, 1, 2, 3, ?)
Since calling .length or .last causes infinite loop,how can I get value "3" (last calculated value) in most efficient way?
You cannot. This is not part of the API of Stream
. And with reason, because that would allow you to observe a value that changes over time from a Stream
, and that violate the (lazy) immutable nature of Stream
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With