1

The following code hangs when it get to the second runRand. Why?

import Control.Monad.Random (Rand, getRandom, runRand)
import System.Random        (RandomGen, mkStdGen)

rgen :: (RandomGen g) => Rand g [Int]
rgen = do
    r <- sequence (repeat getRandom)
    return $ take 5 r

main = do
  let g0 = mkStdGen 0
      (i,g1) = runRand rgen g0 
  print i

  print "one done"

  let (j,_) = runRand rgen g1 
  print j

Based on the answer to this question : Infinite random sequence loops with randomIO but not with getRandom I would have expected the lazy nature of getRandom to allow this program to terminate.

Dave Compton
  • 1,421
  • 1
  • 11
  • 18
  • 1
    What is the state of the random number generator after running it an infinite number of times? I believe that is essentially what you are asking for when you try to get `g1`. – David Young Nov 24 '17 at 23:25

1 Answers1

3

Asking for the value of g1 essentially asks for the state of the random number generator after it runs for an infinite number of times

You can get an idea that this is the case from specializing the type signature of sequence:

sequence :: [Rand g Int] -> Rand g [Int]

The Int list it gives is infinite but it gives back a single random number generator state (the g in the signature). This would have to be the state of the generator after running it enough times to get all the Ints in the list (here, an infinite number of times).

David Young
  • 10,713
  • 2
  • 33
  • 47