[Haskell-cafe] Random numbers / monads - beginner question

Brent Yorgey byorgey at gmail.com
Thu May 8 07:45:23 EDT 2008

2008/5/8 Thomas Dinsdale-Young <thomas-haskell at d-y.me.uk>:

> Madoc wrote:
> Given a list of numbers, I want to modify each of those numbers by adding a
> random offset. However, each such modified number shall stay within certain
> bounds, given by the integers minValue and maxValue. After that, I want to
> continue computation with the resulting list of type [Int].
> Personally, I'd do something like this, isolate the IO code outside the
> algorithm to keep the algorithm pure:
> modify' :: Int -> Int -> Int
> modify' offset a =  normalize (a + offset)
> generateInfiniteListOfRandomNumbers :: IO [Int]
> -- implementation left as an exercise
> main = do
>   randomNumbers <- generateInfiniteListOfRandomNumbers
>   print $ zipWith modify' randomNumbers [0, 200, 400, 600, 800, 1000]
> I may be wrong, but generateInfiniteListOfRandomNumbers won't terminate
> and I think it has to before the next IO action occurs.  (Laziness is great,
> but I don't think you can really do lazy IO like that.)

Sure it will.  You're right that you cannot do lazy IO like this, but no
lazy IO needs to happen here.  The key is that an IO action does not have to
be performed in order to generate each element of the list -- one IO action
is performed at the beginning to produce a random generator, and then this
generator is used (functionally and purely) to produce a lazy infinite list
of pseudorandom numbers.  For example see the 'newStdGen' and 'randoms'
functions from System.Random.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20080508/968cccb3/attachment.htm

More information about the Haskell-Cafe mailing list