Skip to content

Instantly share code, notes, and snippets.

@parallelepiped
Last active October 11, 2015 20:05
Show Gist options
  • Save parallelepiped/fa028d7ceaf58a27e23e to your computer and use it in GitHub Desktop.
Save parallelepiped/fa028d7ceaf58a27e23e to your computer and use it in GitHub Desktop.
Some of the State exercises
trait RNG {
def nextInt: (Int, RNG) // Should generate a random `Int`. We'll later define other functions in terms of `nextInt`.
}
object RNG {
type Rand[+A] = RNG => (A, RNG)
// ?? What does _ mean in this syntax? Access to the RNG trait?
val int: Rand[Int] = _.nextInt
// Define ints with a non-tail recursion
// Why does rng go up by 2??
// Does this therefore have a bug, where we wind up using `r2` "by accident" in the next (recursive) call to `ints`?
def ints(count: Int)(rng: RNG): (List[Int], RNG) =
if (count == 0) (Nil, rng)
else {
val (i, r1) = rng.nextInt
val (l, r2) = ints(count - 1)(r1)
(i :: l, r2)
}
// Unpacking values (a pattern match doesn't make sense here)
def map2[A,B,C](ra: Rand[A], rb: Rand[B])(f: (A, B) => C): Rand[C] =
rng => {
val (a, r1) = ra(rng)
val (b, r2) = rb(r1)
(f(a,b), r2)
}
def flatMap[A,B](f: Rand[A])(g: A => Rand[B]): Rand[B] =
// Destructured assignments require 2 lines of code
// 2 lines of code require being wrapped in braces
rng => {
val (a, r2) = f(rng)
g(a)(r2)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment