Skip to content

Instantly share code, notes, and snippets.

@shomah4a
Created January 15, 2011 09:35
Show Gist options
  • Save shomah4a/780810 to your computer and use it in GitHub Desktop.
Save shomah4a/780810 to your computer and use it in GitHub Desktop.
Actor で Generator
package net.shomah4a.utils.generator.actor
import scala.actors
class GeneratorMessage
object StopIteration
class Yielder[T](postto: actors.Actor, msgobj: GeneratorMessage)
{
def ! (v: T)
{
postto ! (msgobj, v)
}
}
class Generator[T](genfunc: (Yielder[T])=>Unit) extends Iterator[T]
{
private val self = actors.Actor.self
private object message extends GeneratorMessage
private val actor = actors.Actor.actor
{
val msger = new Yielder[T](this.self, message)
genfunc(msger)
this.self ! (this.message, StopIteration)
}
private var nextValue: Option[T] = None
def iterate()
{
this.nextValue = this.self.receive
{
case (this.message, StopIteration) =>
{
None
}
case (this.message, v: T) => Some(v)
}
}
this.iterate
def hasNext() = this.nextValue != None
def next() =
{
val ret = this.nextValue.get
this.iterate
ret
}
}
object Generator
{
def gen[T](func: Yielder[T] => Unit) = new Generator[T](func)
def apply[T] = gen[T] _
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment