Skip to content

Instantly share code, notes, and snippets.

object Main {
def toStreamWithThread[T](generator: (T=>Unit)=>Unit): Stream[T] = {
val queue = new java.util.concurrent.SynchronousQueue[Option[T]]
new Thread(
new Runnable {
def run() {
generator { (Some(_:T)) andThen (queue.put(_)) }
queue.put(None)
}
def toStream[T](generator: => T): Stream[T] = {
def s: Stream[T] = {
val v = generator
if (v == null) Stream.empty else Stream.cons(v, s)
}
s
}
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