27

如何yield return使用 Scala 延续来实现 C#?我希望能够以Iterator相同的风格编写 Scala 。在这篇 Scala 新闻帖子的评论中有一个刺,但它不起作用(尝试使用 Scala 2.8.0 beta)。相关问题中的答案表明这是可能的,但尽管我已经玩了一段时间的定界延续,但我似乎无法完全理解如何做到这一点。

4

2 回答 2

41

在我们介绍延续之前,我们需要建立一些基础设施。下面是一个对物体进行操作的蹦床。Iteration迭代是一种计算,可以是Yield新值,也可以是Done

sealed trait Iteration[+R]
case class Yield[+R](result: R, next: () => Iteration[R]) extends Iteration[R]
case object Done extends Iteration[Nothing]

def trampoline[R](body: => Iteration[R]): Iterator[R] = {
  def loop(thunk: () => Iteration[R]): Stream[R] = {
    thunk.apply match {
      case Yield(result, next) => Stream.cons(result, loop(next))
      case Done => Stream.empty
    }
  }
  loop(() => body).iterator
}

蹦床使用内部循环将Iteration对象序列转换为Stream. 然后我们Iterator通过调用iterator生成的流对象来获得一个。通过使用Stream我们的评估是懒惰的;在需要之前,我们不会评估我们的下一次迭代。

蹦床可用于直接构建迭代器。

val itr1 = trampoline {
  Yield(1, () => Yield(2, () => Yield(3, () => Done)))
}

for (i <- itr1) { println(i) }

这写起来很糟糕,所以让我们使用定界的延续来Iteration自动创建我们的对象。

我们使用shiftandreset运算符将计算分解为Iterations,然后使用trampolineIterations 转换为 a Iterator

import scala.continuations._
import scala.continuations.ControlContext.{shift,reset}

def iterator[R](body: => Unit @cps[Iteration[R],Iteration[R]]): Iterator[R] =
  trampoline {
    reset[Iteration[R],Iteration[R]] { body ; Done }
  }

def yld[R](result: R): Unit @cps[Iteration[R],Iteration[R]] =
  shift((k: Unit => Iteration[R]) => Yield(result, () => k(())))

现在我们可以重写我们的例子。

val itr2 = iterator[Int] {
  yld(1)
  yld(2)
  yld(3)
}

for (i <- itr2) { println(i) }

好多了!

现在这里有一个来自C# 参考页面的示例,yield它显示了一些更高级的用法。这些类型可能有点难以适应,但一切正常。

def power(number: Int, exponent: Int): Iterator[Int] = iterator[Int] {
  def loop(result: Int, counter: Int): Unit @cps[Iteration[Int],Iteration[Int]] = {
    if (counter < exponent) {
      yld(result)
      loop(result * number, counter + 1)
    }
  }
  loop(number, 0)
}

for (i <- power(2, 8)) { println(i) }
于 2010-02-06T23:34:53.427 回答
5

在玩了几个小时之后,我设法找到了一种方法来做到这一点。我认为这比我迄今为止看到的所有其他解决方案更容易理解,尽管我后来非常欣赏 Rich 和Miles 的解决方案。

def loopWhile(cond: =>Boolean)(body: =>(Unit @suspendable)): Unit @suspendable = {
  if (cond) {
    body
    loopWhile(cond)(body)
  }
}

  class Gen {
    var prodCont: Unit => Unit = { x: Unit => prod }
    var nextVal = 0
    def yld(i: Int) = shift { k: (Unit => Unit) => nextVal = i; prodCont = k }
    def next = { prodCont(); nextVal }
    def prod = {
      reset {
        // following is generator logic; can be refactored out generically
        var i = 0
        i += 1
        yld(i)
        i += 1
        yld(i)
        // scala continuations plugin can't handle while loops, so need own construct
        loopWhile (true) {
          i += 1
          yld(i)
        }
      }
    }
  }
  val it = new Gen
  println(it.next)
  println(it.next)
  println(it.next)
于 2010-02-07T22:11:51.630 回答