LazyList .scanLeft()调用了一个空列表

时间:2019-06-14 08:50:26

标签: scala functional-programming lazylist

当我发现解决#2问题的优雅方法时,我一直在Scala中做一些Euler问题。但是,我在理解它为什么起作用时遇到了一些问题。据我所知,它需要1并将其添加到fibbonaciNumbers.scanLeft(1)(_ + _)中以初始化同一数组。怎么可以调用scanLeft()和目前为空的LazyList?

/**
  * Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2,
  * the first 10 terms will be:
  * 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
  * By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the
  * even-valued terms.
  *
  * Result:
  */
object Problem2 {

  def main(args: Array[String]): Unit = {
    println("The result is " + fibbonaciNumbersSum(4000000))
  }

  // Why is it possible to call .scanLeft on an empty list (because it's empty in the moment we call it, right?)
  lazy val fibbonaciNumbers: LazyList[Int] = 1 #:: fibbonaciNumbers.scanLeft(1)(_ + _)

  private def fibbonaciNumbersSum(limit: Int) = fibbonaciNumbers.takeWhile(_ <= limit).filter(_ % 2 == 0).sum
}

1 个答案:

答案 0 :(得分:2)

LazyList不为空。查看Stream的文档:

/** Construct a stream consisting of a given first element followed by elements
 *  from a lazily evaluated Stream.
 */
def #::[B >: A](hd: B): Stream[B] = cons(hd, tl)

因此至少您的Stream / LazyList具有第一个元素(已评估),并且是

中的1
1 #:: fibbonaciNumbers.scanLeft...

列表中的第二个元素是scanLeft ...中的1,然后scanLeft接管以生成其余元素2、3、5 ...,但是只有在需要时才对其进行评估。但是何时需要它们? ...当您致电

println("The result is " + fibbonaciNumbersSum(4000000))

这将触发对

的评估
fibbonaciNumbers.takeWhile(_ <= limit).filter(_ % 2 == 0).sum

因此,将评估Stream / LazyList中的每个元素,只要它们小于限制,就将进行过滤和求和。