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

Henning Thielemann lemming at henning-thielemann.de
Thu May 8 08:36:21 EDT 2008


On Thu, 8 May 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]. But for
> demonstration, I made a program that just prints out the list:
>
>
> import IO; import Random
>
> minValue = 0::Int
> maxValue = 1000::Int
>
> normalize a | a < minValue = minValue
>            | a > maxValue = maxValue
>            | otherwise = a


normalize = min maxValue . max minValue


> modify a = do
>  offset <- randomRIO(-100::Int, 100)
>  return(normalize(a + offset))


Stay away from IO whereever possible, use randomR instead.
Say
   map normalize (zipWith (+) (randomRs (-100::Int, 100)) x)

http://haskell.org/haskellwiki/Humor/Erlkönig
http://haskell.org/haskellwiki/Things_to_avoid#Separate_IO_and_data_processing


More information about the Haskell-Cafe mailing list