Skip to content

Instantly share code, notes, and snippets.

@nkgm
Last active August 29, 2015 14:20
Show Gist options
  • Save nkgm/e44e64a09ec09ef14904 to your computer and use it in GitHub Desktop.
Save nkgm/e44e64a09ec09ef14904 to your computer and use it in GitHub Desktop.
Principles of Reactive Programming - Generators Desugared
trait Generator[+T] {
self =>
def generate: T
def map[S](f: T => S): Generator[S] = new Generator[S] {
def generate = f(self.generate)
}
def flatMap[S](f: T => Generator[S]): Generator[S] = new Generator[S] {
def generate = f(self.generate).generate
}
}
object Generator {
val rand = new java.util.Random()
val integers: Generator[Int] = new Generator[Int] {
def generate = rand.nextInt()
}
val booleans = for (x <- integers) yield x > 0
val booleans_desugared = integers.map { (x) => x > 0 }
def single[T](x: T): Generator[T] = new Generator[T] {
def generate = x
}
def pairs[T, U](t: Generator[T], u: Generator[U]): Generator[(T, U)] = for {
x <- t
y <- u
} yield (x, y)
def pairs_desugared[T, U](t: Generator[T], u: Generator[U]): Generator[(T, U)] =
t.flatMap[(T, U)] {
(x: T) => u.map[(T, U)](
(y: U) => (x, y)
)
}
def choose(lo: Int, hi: Int): Generator[Int] =
for (x <- integers) yield lo + x % (hi - lo)
def choose_desugared(lo: Int, hi: Int): Generator[Int] = integers.map { (x) => lo + (x % (hi - lo)) }
def oneOf[T](xs: T*): Generator[T] =
for (idx <- choose(0, xs.length)) yield xs(idx)
def oneOf_desugared[T](xs: T*): Generator[T] = choose(0, xs.length).map { (idx) => xs(idx) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment