Infinite streams in Scala

Luigi Plinge picture Luigi Plinge · Jun 20, 2011 · Viewed 28.8k times · Source

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.)

Answer

Kim Stebel picture Kim Stebel · Jun 20, 2011
Stream.from(1)

creates a stream starting from 1 and incrementing by 1. It's all in the API docs.