Skip to content

Instantly share code, notes, and snippets.

Created January 14, 2011 13:25
Show Gist options
  • Save anonymous/779600 to your computer and use it in GitHub Desktop.
Save anonymous/779600 to your computer and use it in GitHub Desktop.
Generator みたいななにか
package net.shomah4a.utils.generator
import scala.util.continuations.{reset, shift, cpsParam}
object Generator
{
type GenParam[T] = (Option[T], Option[GeneratorSupport[T]])
def gen[T](f: () => Unit@cpsParam[GenParam[T], GenParam[T]]) = new Generator[T](f)
def yld[T](v: T) =
{
shift[Unit, GenParam[T], GenParam[T]] {ctx: (Unit => GenParam[T]) =>
{
(Some(v), Some(new GeneratorSupport[T]({() => ctx()}))).asInstanceOf[GenParam[T]]
}}
}
}
class GeneratorSupport[T](f: (() => (Option[T], Option[GeneratorSupport[T]])))
{
def apply() = f()
}
class Generator[T](f: () => Unit @cpsParam[Generator.GenParam[T], Generator.GenParam[T]]) extends Iterator[T]
{
var x = reset {
f()
(None, None):Generator.GenParam[T]
}:Generator.GenParam[T]
var value: Option[T] = x._1
var context: Option[GeneratorSupport[T]] = x._2
def hasNext() =
{
context != None
}
def next() =
{
val prev = this.value
val (v, ctx) = (this.context.get)()
this.value = v
this.context = ctx
prev.get
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment