[Haskell-beginners] Creating lists of random numbers

Tom Hobbs tvhobbs at googlemail.com
Thu Oct 21 08:58:45 EDT 2010


Hi all,

I'm trying to create a list of random integers (either 0s or 1s).
I've got one way to work, but I'm trying to use replicate to replace
this implementation but it's not going well.  Can anyone help, please?

Here's the version I want to replace;

ugly :: Int -> [Int]
ugly 0 = []
ugly s = ugly (s-1) ++ [ran]
	where
	ran = unsafePerformIO (randomRIO (0,1)) :: Int

This one works as expected.

Here's the broken version;

broken :: Int -> [Int]
broken s = replicate s ran
	where
	ran = unsafePerformIO (randomRIO (0,1)) :: Int

The problem with broken is that "ran" seems to be evaluated once and
then replicated, so my list contains the same random number s times.
I'd like it to be re-evaluated with each replication.

Also, I've heard of the dangers of using unsafePerformIO.  Can anyone
suggest a different way to generate random numbers?

(Finally, a question that doesn't involve serialisation!)

Cheers,

Tom


More information about the Beginners mailing list