Home > OS >  Use Haskell's Control.Monad.Random.Class.fromList with System.Random
Use Haskell's Control.Monad.Random.Class.fromList with System.Random

Time:11-12

I want to use Control.Monad.Random.Class.fromList

fromList :: MonadRandom m => [(a, Rational)] -> m a

https://hackage.haskell.org/package/MonadRandom-0.5.3/docs/Control-Monad-Random-Class.html#v:fromList

together with System.Random.mkStdGen

mkStdGen :: Int -> StdGen

https://hackage.haskell.org/package/random-1.2.1/docs/System-Random.html#v:mkStdGen

I see the instance

(Monad m, RandomGen g) => MonadInterleave (RandT g m)

but am not sure how to combine.

CodePudding user response:

You need to use a monad that has an instance of MonadRandom, such as RandT:

import System.Random
import Control.Monad.Random

main :: IO ()
main = do
  let stdGen = mkStdGen 2021
  putStrLn $ fst $
    runRand (fromList [("hello", 0.5), ("world", 0.1)]) stdGen

Which will yield:

world
  • Related