leftaroundabout
leftaroundabout

Reputation: 120741

How to sample random values in an ST monad?

If I have a random value generator in the RVar monad

ranfu :: RVar Bool

and a higher-order function that does some kind of traversal in (e.g.) the ST monad

stTrav :: PrimMonad m => (Int -> m b) -> m [b]

then how could I use ranfu in the loop of this traversal? Do I need to channel the state of the RVar through an STRef, or is there a better way?

Upvotes: 2

Views: 159

Answers (1)

shang
shang

Reputation: 24832

The simplest way is probably to use the RandomSource instance for ST in Data.Random.Source.MWC:

import Data.Random.Source.MWC

sample :: [Bool]
sample = runST $ do
  g <- create
  stTrav (\i -> runRVar ranfu g)

Upvotes: 1

Related Questions