How to create MonadRandom (StateT PureMT m0)? (Haskell)

I am trying to use MonadRandom

from https://hackage.haskell.org/package/random-fu-0.2.6.0/docs/Data-Random.html#g:6

Specifically, I have a function with a type signature:

randomN :: MonadRandom m => m Int

and I want to run it with the Mersenne Twister with the famous seed.

How do I create an "instance Monad m0 => MonadRandom (StateT PureMT m0)

from the documentation?"

+3


source to share


2 answers


Since an instance for MonadRandom

already exists for Monad m => StateT PureMT m

, you just need something like

-- State s a = StateT s Identity a
test :: State PureMT (Int, Int)
test = do
    a <- randomN
    b <- randomN
    return (a, b)

      



And you can run it like

main :: IO ()
main = do
    -- You can replace 1234 with whatever seed you want
    let (result, finalState) = runState test $ pureMT 1234
    putStr "The result: "
    print result
    putStr "The final state: "
    print finalState

      

+4


source


Ok I figured out how to solve my problem.

Since the documentation for MonadRandom

states that a StateT PureMT m0

can be thought of as MonadRandom, we can "pretend" to randomN

actually return a StateT PureMT m0

. We will choose m0

as a single monad, in other words, we can act as if it randomN

had the signature



randomN :: StateT PureMT Identity Int

Now, to return the value, we simply expand: runIdentity (evalStateT (randomN) $ pureMT seed)

0


source







All Articles