I need multiple random numbers in different ranges (which could be avoided by multiplying the result of the random number generator with a constant).
I\'m making an Aste
The usual pattern when you want to generate multiple random numbers in Haskell goes like this:
foo :: StdGen -> (StdGen, (Int, Int, Int))
foo g0 = let
(val1, g1) = randomR (0, 10) g0
(val2, g2) = randomR (0, 10) g1
(val3, g3) = randomR (0, 10) g2
in (g3, (val1, val2, val3))
For example, in ghci:
System.Random> foo (mkStdGen 0)
(1346387765 2103410263,(7,10,2))
You can see it returned three different numbers -- unlike what you would get if you called randomR
with g0
each time as you did in your code.
Hopefully you catch the pattern: call randomR
with the range you want and a StdGen
; use the value it returned as your random piece and the StdGen
it returned as the input next time you call randomR
. It's also important that you return the updated StdGen
from your random function, so that you can continue the pattern in later calls.
Later you can look into monads, specifically RandT, which can abstract away the process of feeding the most recently updated StdGen
into the next call to randomR
. A sample of the RandT
style looks like this:
foo' :: MonadRandom m => m (Int, Int, Int)
foo' = do
val1 <- getRandomR (0, 10)
val2 <- getRandomR (0, 10)
val3 <- getRandomR (0, 10)
return (val1, val2, val3)
...but for now, stick with the basics. Once you understand them thoroughly it will feel much less magical when you implement (or reuse) the abstractions that let you do that kind of thing.