
On 1/12/07, Rich Neswold
On 1/12/07, Chad Scherrer
wrote: Even if I use randomIO outside the STM code, I don't know of a (safe) way to bring it in.
Define your STM action to be (Int -> STM s). Generate the random number and then pass it in:
mySTM :: Int -> STM a mySTM n = do { ... }
To use it:
do { n <- getStdRandom (...) ; atomically (mySTM n) }
Anyway, the number of random values needed depends on other stuff going on within the STM part.
Ah. This detail removes my suggestion. But how about this?
randomizer :: TMVar Int -> IO () randomizer v = do { n <- getStdRandom (...) ; atomically (putTMVar v n) ; randomizer v }
Start the randomizer action using forkIO. This gives you a steady supply of random numbers in the STM monad just by reading the TMVar (via takeTMVar).
Rather than having a separate thread computing the random numbers using IO, why not just stick an StdGen in a TVar and write a function like: type RandomVar = TVar StdGen rnd :: RandomVar -> STM a rnd var = do g <- readTVar var let (r,g') = random g writeTVar var g' return r -- Sebastian Sylvan +46(0)736-818655 UIN: 44640862