Skip to content

Instantly share code, notes, and snippets.

@jsuereth
Created February 21, 2011 22:11
Show Gist options
  • Save jsuereth/837798 to your computer and use it in GitHub Desktop.
Save jsuereth/837798 to your computer and use it in GitHub Desktop.
First cut at attempting to support CPS plugin and collections.
import collection.generic.CanBuildFrom
import util.continuations._
class SuspendableProxy[+T, +Repr <: Iterable[T]](xs: Repr)(implicit cbf : CanBuildFrom[Repr, T, Repr]) {
private[this] def newBuilder = cbf()
def foreach[A](body: T => Unit @cps[A]): Unit @cps[A] = {
val it = xs.iterator
while (it.hasNext) {
body(it.next)
}
}
def map[B, A, To](f : T => B @cps[A])(implicit bf : CanBuildFrom[Repr, B, To]) : To @cps[A] = {
val b = bf()
b.sizeHint(xs)
val it = xs.iterator
while (it.hasNext) {
b += f(it.next)
}
b.result
}
def filter[A](f : T => Boolean) : Repr @cps[A] = {
val it = xs.iterator
val b = newBuilder
b.sizeHint(xs)
while (it.hasNext) {
val elem = it.next
if (f(elem))
b += elem
}
b.result
}
def flatMap[B, A, To](f : T => Iterable[B] @cps[A])(implicit bf : CanBuildFrom[Repr, B, To]) : To @cps[A] = {
val it = xs.iterator
val b = bf()
b.sizeHint(xs)
while (it.hasNext) {
b ++= f(it.next)
}
b.result
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment