Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@grzesiak
Created September 27, 2010 18:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save grzesiak/599575 to your computer and use it in GitHub Desktop.
Save grzesiak/599575 to your computer and use it in GitHub Desktop.
import scala.util.continuations._
class Generator[A] extends Iterator[A] with (A => Unit @ suspendable) {
private var a: Option[A] = None
private var k: Option[Unit => Unit] = None
def next = {
val a0 = a.get
val k0 = k.get
a = None
k = None
k0()
a0
}
def hasNext = k.isDefined
def apply(a0: A): Unit @ suspendable = {
a = Some(a0)
shift { k0: (Unit => Unit) => k = Some(k0) }
}
}
object Generator {
trait SuspendableIterable[A]{
def foreach( f: A => Unit @ suspendable ) : Unit @ suspendable
}
def generator[A]( f: (A => Unit @ suspendable) => Unit @ suspendable): Iterator[A] = {
val g = new Generator[A]
reset { f(g) }
g
}
def suspendable[A]( ible: Iterable[A]) = new SuspendableIterable[A] {
def foreach( f: A => Unit @ suspendable ) : Unit @ suspendable = {
val i = ible.iterator
while( i.hasNext ) f(i.next)
}
}
}
object Main {
import Generator._
def data(block: Int => Unit) {
for (i <- 0 to 10) block(i)
}
def main(args: Array[String]) {
val dataStream = generator[Int] { yld =>
data { i => yld(i) }
}.toStream
dataStream.foreach { println(_) }
}
}
@dcsobral
Copy link

Data needs to be changed this way for it to work:

def data(block: Int => Unit @ suspendable): Unit @ suspendable = {
  var i = 0
  while(i <= 10) {
    block(i)
    i += 1
  }
}

So, no, you can't take a non-suspendable method and suspend it using delimited continuations. It just doesn't work that way.

@grzesiak
Copy link
Author

That's the problem, because I can't change the implementation of data function.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment