当我找到#2 问题的非常优雅的解决方案时,我一直在 Scala 中做一些欧拉问题。但是,我在理解它为什么起作用时遇到了一些问题。据我所知,它需要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
}