scala中使用收益率的返回和可重用集合
我在Scala中有一个DateTime和TimeSpan类(假设<和+运算符按它们应该的方式工作)。我试图定义一个“range”函数,它需要一个开始/停止时间和一个步进时间跨度。在C#中,我会以收益率来做这件事,我认为我应该能够在Scala中做同样的事情。。。除了我有个奇怪的错误 在“收益率t”行,我得到了“声明的非法开始”scala中使用收益率的返回和可重用集合,scala,loops,yield-return,yield-keyword,Scala,Loops,Yield Return,Yield Keyword,我在Scala中有一个DateTime和TimeSpan类(假设
def dateRange(从:DateTime,到:DateTime,步骤:TimeSpan)=
{
//不确定列表中的方法是什么
var t=来自
while(t
看看这段代码,我对两件事很好奇:
1) 我做错了什么?
2) 编写的代码非常必要(使用var t等)。在Scala中,哪一种功能更强大的方法可以相当快地实现这一点
谢谢 在Scala中,
yield
是for循环的特殊语句
我不知道C#,但据我所知,我认为最简单的方法是使用collection.immutable.numeriRange.Exclusive[DateTime]
或collection.immutable.numeriRange.Inclusive[DateTime]
,这取决于您的间隔是独占的还是包含的
为此,您需要创建一个Integral[DateTime]
实例,该实例定义类型DateTime
def dateRange(from:DateTime,to:DateTime,step:TimeSpan):迭代器[DateTime]=
def dateRange(from : DateTime, to : DateTime, step : TimeSpan): Iterator[DateTime] =
Iterator.iterate(from)(_ + step).takeWhile(_ <= to)
Iterator.iterate(from)(+步骤).takeWhile(以下是带有joda时间段的@Debilski解决方案的一个版本:
import org.joda.time.{DateTime, Period}
def dateRange(from: DateTime, to: DateTime, step: Period): Iterator[DateTime] =
Iterator.iterate(from)(_.plus(step)).takeWhile(!_.isAfter(to))
如果我能给你+1000,我会的。那太棒了。好吧,Integral
在DateTime
中实现似乎有点愚蠢。另一种方法是使用Iterator.iterate
更好。Scala中的yield
与C(或Python)中的yield
没有任何关系。此外,Scala没有与之等价的东西--查找有关Scala、Python、yield和生成器的许多问题。当然,还可以查找关于yield
实际做了什么的问题。我做了,但我感到困惑。Debilski的回答告诉了我需要知道的一切。
import org.joda.time.{DateTime, Period}
def dateRange(from: DateTime, to: DateTime, step: Period): Iterator[DateTime] =
Iterator.iterate(from)(_.plus(step)).takeWhile(!_.isAfter(to))