Infinite streams in Scala

后端 未结 5 1566
忘了有多久
忘了有多久 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:24

    The original "factorial" function is not optimal, since factorials are computed from scratch every time. The simplest/immutable implementation using memoization is like this:

    val f : Stream[BigInt] = 1 #:: (Stream.from(1) zip f).map { case (x,y) => x * y }
    

    And now, the answer can be computed like this:

    println( "count: " + (f takeWhile (_

提交回复
热议问题