Skip to content

Instantly share code, notes, and snippets.

@derekjw
Created May 2, 2011 14:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save derekjw/951681 to your computer and use it in GitHub Desktop.
Save derekjw/951681 to your computer and use it in GitHub Desktop.
Roland's Generator
import scala.util.continuations._
import scala.util.Random
class Generator[+T](f : () => T) {
def apply() : T @cps[Generator[Any]] = shift { this flatMap _ }
def generate(n : Int) : IndexedSeq[T] = 0 to n map (x => get)
def get = f()
def flatMap[TT](ff : T => Generator[TT]) = new Generator( () => ff(get).get )
def map[TT](ff : T => TT) = new Generator( () => ff(get) )
}
object Generator {
def apply[T](body : => T @cps[Generator[T]]) : Generator[T] = reset {
val x = body
new Generator[T]( () => x )
}
}
val genInt = new Generator( () => Random.nextInt )
val genBool = new Generator( () => Random.nextBoolean )
case class A(x : Int, b : Boolean)
val genA = Generator( A(genInt(), genBool()) )
genA generate 10 foreach println
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment