2008/5/8 Thomas Dinsdale-Young <[email protected]
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
bounds, given by the integers minValue and maxValue. After that, I want
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
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