vendredi 24 juillet 2015

How do I generate a random number using functional state?

I'm struggling to figure out how to merge a functional representation of State with Scala's Random class to generate random integers. I'm studying from the book Functional Programming in Scala, and so most of the code is taken from there.

Here's what the State class looks like, directly from the book:

case class State[S, +A](run: S => (A, S))

And here's what I want to do:

object State {
  type Rand[A] = State[A, Random] // the Random from scala.util.Random

  def nextIntInRange(from: Int, to: Int): Rand[Int] =
  ??? _.nextInt(from - to) + from ??? // unsure about much of this

  def get(a: Rand[A]): A = ??? // also unsure; should modify state

  def getAndPreserveState(a: Rand[A]): A = ??? // ditto; should not modify state

  def diceRolls(n: Int) = {
    val roll = nextIntInRange(1, 6) 
    go(n: Int, acc: List[Int]): List[Int] = {
      if (n >= 0) go(n-1, get(roll) :: acc) else acc
    }
    go(n, List())
  }

My goal is to be able to use diceRolls with any sized integer and for any given starting seed and generate a list of integers that does not ever change. In other words, diceRolls(3) might be List(3,3,2), and if so, rewriting it as diceRolls(7).take(3) must result again in List(3,3,2), and so on.




Aucun commentaire:

Enregistrer un commentaire