【问题标题】:Returning and iterable collection using yield in scala在scala中使用yield返回和可迭代的集合
【发布时间】:2023-03-14 11:20:01
【问题描述】:

我在 Scala 中有一个 DateTime 和 TimeSpan 类(假设

在 'yield t' 行,我得到“Illegal start of statement”。

  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 中,有什么更实用的方法可以相当快地做到这一点?

谢谢!

【问题讨论】:

  • Scala 中的 yield 与 C#(或 Python)中的 yield 没有任何关系。此外,Scala 没有它的等价物——查看有关 Scala、Python、yield 和生成器的许多问题。当然,还要查找有关 yield 实际作用的问题。
  • 我做到了,我很困惑。 Debilski 的回答告诉了我所有我需要知道的。

标签: scala loops yield-return yield-keyword


【解决方案1】:

这是带有 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】:
    def dateRange(from : DateTime, to : DateTime, step : TimeSpan): Iterator[DateTime] =
      Iterator.iterate(from)(_ + step).takeWhile(_ <= to)
    

    【讨论】:

    • 如果我能给你+1000,我会的。太棒了。
    【解决方案3】:

    在 Scala 中,yield 是 for 循环的特殊语句。

    我不懂 C#,但据我了解,我认为对你来说最简单的方法是使用 collection.immutable.NumericRange.Exclusive[DateTime]collection.immutable.NumericRange.Inclusive[DateTime],这取决于你的区间是独占还是包含。

    为此,您需要创建一个 Integral[DateTime] 的实例,它定义了 DateTime 类型的算法。

    【讨论】:

    • 好吧,Integral 似乎对DateTime 实施有点愚蠢。 Iterator.iterate 的另一种方法要好得多。
    猜你喜欢
    • 1970-01-01
    • 2011-02-17
    • 2010-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-02
    • 2011-01-09
    • 1970-01-01
    相关资源
    最近更新 更多