[Haskell-cafe] STM and random numbers

Robert Dockins robdockins at fastmail.fm
Fri Jan 12 12:07:07 EST 2007

On Jan 12, 2007, at 10:58 AM, Chad Scherrer wrote:

> Hi,
> I'd like to be able to use randomIO, but I'm working within the
> context of STM. Is there a way to get these working together happily?
> For now, I guess I could kludgingly use unsafePerformIO inside STM
> (it's the other way around that's not allowed, right?), but I would
> need to be sure it doesn't get inlined.

Humm... I'd actually suggest you stop trying to break the rules, and  
use the portion of the random interface that doesn't require IO.  You  
can pretty easily wrap a StdGen using StateT, and write your stuff in  
the monad (StateT StdGen STM).

Or, (and I'm amazed this hasn't been done before), you can create a  
custom random monad that wraps up this behavior.  Prototype  
attached.  Now you can write in (RandT StdGen STM), and use the  
convenient getRandom method.

Invoke like:

dostuff :: IO ()
dostuff = do
     gen <- newStdGen
     x <- atomically (evalRandT stuff gen)
     process x

stuff :: RandT StdGen STM Int
stuff = do
      r <- getRandom
      lift (someSTMaction r)

> Thanks,
> Chad

Rob Dockins

Speak softly and drive a Sherman tank.
Laugh hard; it's a long way to the bank.
           -- TMBG

-------------- next part --------------
A non-text attachment was scrubbed...
Name: Random.hs
Type: application/octet-stream
Size: 1207 bytes
Desc: not available
Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070112/eefa279e/Random.obj
-------------- next part --------------

More information about the Haskell-Cafe mailing list