使用scala中的yield返回和迭代集合

时间:2011-10-28 12:49:38

标签: scala loops yield-return yield-keyword

我在Scala中有一个DateTime和TimeSpan类(假设<和+运算符可以正常工作)。我正在尝试定义一个'范围'函数,它采用开始/停止时间和步进的时间跨度。在C#中我会以收益率来做这个,我想我应该能够在Scala中做同样的事情......除了我得到一个奇怪的错误。

在'yield t'行,我得到“非法开始陈述”。

  def dateRange(from : DateTime, to : DateTime, step : TimeSpan) =
  {
      // not sure what the list'y way of doing this is
    var t = from

    while(t < to)
    {
      yield t; // error: illegal start of statement
      t = t + step
    }
  }

看看这段代码,我很好奇两件事: 1)我做错了什么? 2)编写的代码非常必要(使用var t等)。在Scala中以更快的速度执行此操作的功能是什么?

谢谢!

3 个答案:

答案 0 :(得分:17)

def dateRange(from : DateTime, to : DateTime, step : TimeSpan): Iterator[DateTime] =
  Iterator.iterate(from)(_ + step).takeWhile(_ <= to)

答案 1 :(得分:3)

以下是带有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))

答案 2 :(得分:0)

在Scala中,yield是for循环的特殊声明。

我不知道C#,但根据我的理解,我认为对您来说最简单的方法是使用collection.immutable.NumericRange.Exclusive[DateTime]collection.immutable.NumericRange.Inclusive[DateTime],具体取决于您的间隔是独占还是包含。

要使其正常工作,您需要创建Integral[DateTime]的实例,该实例定义类型DateTime的算术。

相关问题