Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala how to get last calculated value of stream?

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?

like image 504
altayseyhan Avatar asked Jan 26 '17 06:01

altayseyhan


1 Answers

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.

like image 60
sjrd Avatar answered Oct 26 '22 18:10

sjrd