My goal is to parallelize a computation using parMap
from the parallel package, but I'd also like to add a bit of randomness to my sampling function.
Without the randomness my calculation is simply some number crunching and so it's pure and I could use parMap
. In order to get good results, I need to take multiple samples at each step and average the results. The sampling needs to be randomized.
One solution might be to use the random package, call randoms
and then consume that list during the computation (by passing the pure lazy list to the computation I would keep it pure). Unfortunately, that's a very slow random number generator and I need a lot of random numbers so I would prefer to use either mwc-random or mersenne-random (although, I don't think mersenne-random is still maintained).
Is it safe to use something like unsafePerformIO
with mwc-random to write a function like randoms
? Something like this:
randomsMWC :: Variate a => GenST s -> [a]
randomsMWC g = unsafePerformIO $ unsafeSTToIO $ randomsMWC' g
where
randomsMWC' g = do
a <- uniform g
as <- unsafeInterleaveST $ randomsMWC' g
return (a : as)
Do I need to instead reach for a parallel number generator? Or do I need to bite the bullet and admit that my algorithm is simply not pure without using the slow random package?
Suggestions? Thanks!