# Random

**Mark Carroll
**
mark@chaos.x-philes.com

*Tue, 17 Dec 2002 08:34:01 -0500 (EST)*

On Tue, 17 Dec 2002, Filipe Santos wrote:
>* I need some help to do a function so that I cant get 4 numbers between 1
*>* and 6, i tried to use random but i can't make it work well.
*
This might be useful,
import Random
dice :: (RandomGen g) => g -> Int -> (g, [Int])
dice rng number_rolls =
(iterate next_roll (rng, [])) !! number_rolls
where
next_roll (rng, rolls) =
let (random_number, new_rng) = next rng
in (new_rng, (mod random_number 6 + 1) : rolls)
main = do rng <- newStdGen -- (or getStdGen or something)
print (snd (dice rng 4))
The "dice" function gives you back the new state of the rng which maybe
you should keep around to start the next set of rolls with. ("main" throws
it away with "snd".) I'd certainly be interested to see how this could be
written more nicely. I avoided making the list of die rolls an infinitely
long lazy list in case we wanted to use the same RNG for other stuff too
and not have the same RNs reused, but I don't know much about how the RNG
stuff is exactly defined.
-- Mark