Created
January 14, 2011 13:25
-
-
Save anonymous/779600 to your computer and use it in GitHub Desktop.
Generator みたいななにか
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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