In a simulation problem, I need to generate thousands of agent objects behaving independantly of each other. For this I need to pass each of these agents a different random number generator. How to do this in Haskell? In a language like C, I can just generate a random number whenever it is needed, but in Haskell I need to do it only in the IO monad. The behaviour of the agents in entirely pure computation.
I am doing it in the following manner now:
import System.Random
main = do
gen1 <- newStdGen
let rands1 = randoms gen :: [Int]
gen2 <- newStdGen
let rands2 = randoms gen :: [Int]
let sout = map (agentRun extraArgs) [rands1,rands2]
writeFile "output" $ unlines sout
agentRun = <<some pure code that uses random numbers>>
One way I could solve this problem is given below, but it suffers from the fact that it requires to be run in IO monad only and I cannot just map the function on a list. Is there a better and more Haskell-like way for doing this? If yes, please give an sample code example.
Please note that the agents require access to infinite list as it is not known in advance how many random numbers are needed.
import System.Random
main = do
dorun 10
dorun 0 = return ()
dorun n = do
gen1 <- newStdGen
let rands1 = randoms gen :: [Int]
let sout = agentRun extraArgs rands1
appendFile "output" sout
dorun (n-1)
agentRun = <<some pure code that uses random numbers>>