如何在Scala for循环中指定"下一个"函数

Ari*_*ies 2 loops for-loop functional-programming scala yield

我有一个这样的代码片段:

val step = Step.Montyly  //this could be Yearly, daily, hourly, etc.
val (lower, upper) = (****, ****) //unix timestamps, which represent a time range 
val timeArray = Array[Long](0)

var time = lower
while (time <= upper) {
    timeArray +: = time
    time = step.next(time) // eg, Step.Hourly.next(time) = time + 3600, Step.Monthly.next(time) = new DateTime(time).addMonths(1).toTimeStamp()
}

return timeArray
Run Code Online (Sandbox Code Playgroud)

虽然这是用Scala编写的,但它是一种非功能性的方式.我是Scala的新手,想知道这是否可以用功能方式重写.我知道以下内容:

for(i <- 1 to 10 by step) yield i
Run Code Online (Sandbox Code Playgroud)

但步骤在这里是固定值,如何使"i"可以通过"下一个函数"而不是固定值生成?

Rea*_*onk 5

您将不得不稍微改变流程以使其正常运行(没有可变Array和没有var).Stream.iterate使用初始起始值,并重复应用函数以生成下一个元素.

Stream.iterate(lower)(step.next).takeWhile(_ < upper)
Run Code Online (Sandbox Code Playgroud)