Iteration
对象的trampoline。迭代是一种计算,它可以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
}
ampoline使用内部循环将Iteration
对象的序列转换为Stream
。然后通过在生成的流对象上调用iterator
来获取Iterator
。使用Stream
可以实现惰性评估;直到需要下一次迭代时,我们才会评估它。跳板可以直接用于构建迭代器。
val itr1 = trampoline {
Yield(1, () => Yield(2, () => Yield(3, () => Done)))
}
for (i <- itr1) { println(i) }
这样写非常糟糕,因此让我们使用分隔的延续来自动创建我们的Iteration
对象。
我们使用shift
和reset
运算符将计算分解为Iteration
,
然后使用trampoline
将Iteration
转换为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#参考页面的示例,演示了一些更高级的用法。 类型可能有点棘手,但它们都可以工作。
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) }
iterator
重命名为 yldIterator
或其他类似的名称,以避免混淆。 :-) - Daniel C. Sobral在玩耍了几个小时后,我设法发现了一种方法来做到这一点。我认为这比我迄今所见到的所有其他解决方案都更容易理解,尽管之后我非常欣赏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)