Reputation: 169
I have previously created this function to generated integers random numbers in a range (m,n)
.
giveRand :: Random c => c -> c -> c
giveRand m n = unsafePerformIO . getStdRandom $ randomR (m,n)
From this situation I wanted to run it multiple times with the same parameters, so that it would return me a list of randomly generated values in the given range. I tried the replicate function, but it only did copy the result of giveRand. It did not create multiple copies of the function and reevaluate it.
From this problem I wondered if there is a function that allows me to run any function multiple times with the same parameters. I ask this for cases such as this one, that even with the same inputs of range, different values may arise.
So, is there any function in Haskell that enables me to run a function multiple times with the same parameters?
Upvotes: 0
Views: 704
Reputation: 153182
Forget unsafePerformIO
; admit that you are doing something stateful. Here's how:
Control.Monad System.Random> replicateM 3 (randomRIO (5,7))
[6,7,5]
If you must not do IO, you can also make the statefulness explicit with the State
monad:
Control.Monad.State System.Random> runState (replicateM 3 (state (randomR (5,7)))) (mkStdGen 0)
([7,7,5],1346387765 2103410263)
Upvotes: 8