[Top] [All Lists]

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

Subject: Re: [Haskell-cafe] Random numbers / monads - beginner question
From: "Brent Yorgey"
Date: Thu, 8 May 2008 07:45:23 -0400

2008/5/8 Thomas Dinsdale-Young <thomas-haskell@xxxxxxxxx>:
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.

Haskell-Cafe mailing list
<Prev in Thread] Current Thread [Next in Thread>