Created
May 2, 2011 14:33
-
-
Save derekjw/951681 to your computer and use it in GitHub Desktop.
Roland's Generator
This file contains hidden or 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
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