H_1317
H_1317

Reputation: 147

Scala Streams and filtering

I have been learning about using Steams instead of lists in Scala for certain scenarios and this seemingly classic scenario has come up in numerous texts:

Suppose we want to find the second prime number in the range 1 to 10000

If we do the following: 1 to 10000 filter(isPrime)(1)

then we are forced to build the entire list of primes within the interval, and only then take the second element from the list.

However, if we use a stream and delay computation of the tail till only when we need it, then we only have to find the first two primes in the range and then can stop our search through the rest of the range.

My question is: How does Scala know that I am only looking for the second prime? Why wouldn't Scala evaluate the expression left to right, then find the second element of the stream? It seems there is a potential for an out of bounds exception if the index call is applied too early, before the stream has calculated enough primes.

I'm sure the compiler somehow translates the expression to take into account the user only wants the element at index = (1), but I'm curious how this actually takes place "under the hood".

Thanks!

Upvotes: 0

Views: 185

Answers (1)

Cyrille Corpet
Cyrille Corpet

Reputation: 5315

Actually, stream(1) is equivalent to stream.drop(1).head.

That is, the index call is not a look-up in an array where value may or may not be yet. It is actually discarding all elements from the first one until the requested one, as it is done in List, or any LinearSeqOptimized for that matter.

Upvotes: 2

Related Questions