StdGen is Haskell’s typical pseudo-random generator state. Create one from a seed, pass it to a generation function, and keep the returned state for the next value. section 9.1.2 section 9.1.3
Use the generator with the main value-generation functions:
- random generates a value through Random and returns the updated generator. section 9.1.3
- randomR generates a Random value within a supplied range. section 9.1.3
- uniform generates uniformly distributed values through Uniform. section 9.1.3
- uniformR generates uniformly distributed values within a range. section 9.1.3
Generating a random list
Define randomListN :: Random a => StdGen -> Int -> ([a], StdGen), recursively call random with the updated generator, and return the final state. A separate randomList function can first choose a bounded length with uniformR. section 9.1.3
Listing 9.3 Functions to produce random lists of random sizes
randomListN :: (Random a) => StdGen -> Int -> ([a], StdGen)
randomListN gen n
| n <= 0 = ([], gen)
| otherwise =
let (v, gen') = random gen #1
(xs, gen'') = randomListN gen' (n - 1) #2
in (v : xs, gen'')
randomList :: (Random a) => StdGen -> Int -> ([a], StdGen)
randomList gen maxVal = randomListN gen' n #3
where
(n, gen') = uniformR (0, maxVal) gen #4
randomList' :: (Random a) => StdGen -> ([a], StdGen)
randomList' = flip randomList 100 #5
Browse the complete random-list definitions, including bounded list lengths and a convenient randomList' specialization. section 9.1.3
StdGen can also be accessed globally inside IO. getStdGen returns a copy, so code using getStdGen and setStdGen must write the modified generator back. For concurrent use, prefer applyAtomicGen with globalStdGen over these deprecated functions. section 9.1.4
Listing 9.5 An IO action that applies a function to the global pseudo-random generator
applyGlobalStdGen :: (StdGen -> (a, StdGen)) -> IO a applyGlobalStdGen f = applyAtomicGen f globalStdGen #1
Browse the compact helper that applies a StdGen transformation to the safer global generator interface. section 9.1.4
