Search code examples
haskellmonadsmonad-transformersstate-monad

How to create a 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 the type signature:

randomN :: MonadRandom m => m Int

and I want to run it using the Mersenne Twister with a known seed.

How to I "create" an instance of Monad m0 => MonadRandom (StateT PureMT m0) from the documentation?


Solution

  • Since the instance for MonadRandom is already there 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 as

    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