Infinite streams in Scala

Viewed 32730

Say I have a function, for example the old favourite

def factorial(n:Int) = (BigInt(1) /: (1 to n)) (_*_)

Now I want to find the biggest value of n for which factorial(n) fits in a Long. I could do

(1 to 100) takeWhile (factorial(_) <= Long.MaxValue) last

This works, but the 100 is an arbitrary large number; what I really want on the left hand side is an infinite stream that keeps generating higher numbers until the takeWhile condition is met.

I've come up with

val s = Stream.continually(1).zipWithIndex.map(p => p._1 + p._2)

but is there a better way?

(I'm also aware I could get a solution recursively but that's not what I'm looking for.)

5 Answers

The following variant does not test the current, but the next integer, in order to find and return the last valid number:

Iterator.from(1).find(i => factorial(i+1) > Long.MaxValue).get

Using .get here is acceptable, since find on an infinite sequence will never return None.

Related