[Haskell] Laziness and the IO Monad (randomness)
Paul Johnson
paul at cogito.org.uk
Thu Mar 1 15:50:33 EST 2007
David Brown wrote:
> Dave Tapley wrote:
>
>
>> This code show a trivial case where randomness (and hence the IO
>> monad) is not used and the first 10 elements of the produced list
>> are printed:
>>
>
> You don't need the IO monad to achieve pseudy-randomness. Why not use
> 'randoms' from System.Random (or 'randomRs' for a range).
>
> take 10 $ (randomRs (1,6) (mkStdGen 1)) :: [Int]
>
The other possibility, which would work better in a non-toy problem, is
to encapsulate the random numbers in a state monad. That way, rather
than using the IO monad (with all its complexity) you can just have a
monad of randomness (along with a Bag of Holding and a +2 sword). The
trick is to use the split operation when you need to do something lazy.
"split" forks the generator into two generators, so you can use one as
the generator in your lazy stream and the other for the next step in
your random computation.
Or you could use "Gen" from Test.QuickCheck, which basically does this
already.
The Wikibook chapter on random numbers explains this.
Paul.
More information about the Haskell
mailing list