Infinite streams in Scala

后端 未结 5 1562
忘了有多久
忘了有多久 2021-02-03 17:28

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

5条回答
  •  独厮守ぢ
    2021-02-03 18:08

    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.

提交回复
热议问题