Skip to content

Instantly share code, notes, and snippets.

@maedaunderscore
Created February 1, 2012 14:43
Show Gist options
  • Save maedaunderscore/1717359 to your computer and use it in GitHub Desktop.
Save maedaunderscore/1717359 to your computer and use it in GitHub Desktop.
continuation
import scala.util.continuations._
object Main extends App{
abstract sealed class Computation[+A]
case class Yielded[A](k: Unit => Computation[A], v: A) extends Computation[A]
case object Done extends Computation[Nothing]
type yieldable[A] = cps[Computation[A]]
def make[A] (body: (A => Unit @yieldable[A]) => Unit @yieldable[A]): Iterator[A] =
new Iterator[A] {
val yields: A => Unit @yieldable[A] = { v =>
shift{k: (Unit => Computation[A]) => Yielded(k, v) }
}
var thunk: Unit => Computation[A] = {x: Unit =>
reset {
body(yields)
Done
}
}
var fetched: Boolean = false
var value: Option[A]= _
def fetch() : Option[A]= {
if(!fetched) {
fetched = true
value = (thunk()) match {
case Yielded(k, v) =>
thunk = k
Some(v)
case Done =>
None
}
}
value
}
def next = {
fetch()
fetched = false
value.get
}
def hasNext = {
fetch()
! value.isEmpty
}
}
val iter = make[Int] { yields =>
def x(i: Int) = {
yields(i)
Thread.sleep(1000)
}
x(1)
x(2)
x(3)
}
iter.foreach(println)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment