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

Thomas Dinsdale-Young thomas-haskell at d-y.me.uk
Thu May 8 07:36:29 EDT 2008


 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.)

Instead of map :: (a -> b) -> [a] -> [b], I think you are looking for mapM
:: Monad m => (a -> m b) -> [a] -> m [b].
* *
* *Hope this helps,
Thomas

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


More information about the Haskell-Cafe mailing list