[Haskell-cafe] STM and random numbers

Rich Neswold rich.neswold at gmail.com
Fri Jan 12 14:35:00 EST 2007

On 1/12/07, Chad Scherrer <chad.scherrer at gmail.com> 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).


AIM : rnezzy
ICQ : 174908475

More information about the Haskell-Cafe mailing list