How to use MonadRandom?

前端 未结 2 612
清歌不尽
清歌不尽 2021-01-01 20:01

Can someone provide \"for-dummies\" example of how to use `MonadRandom\'?

Currently I have code that does stuff like passing around the generator variable, all the w

2条回答
  •  时光说笑
    2021-01-01 20:30

    Basically all the extra g parameters can just be dropped. You then get random numbers using the functions from Control.Monad.Random (such as getRandomR). Here is your example (I added some args to make it compile):

    import Control.Monad.Random
    
    main = do
        g <- getStdGen
        let r = evalRand (myFunc 1 2 3) g :: Double
        -- or use runRand if you want to do more random stuff:
        -- let (r,g') = runRand (myFunc 1 2 3) g :: (Double,StdGen)
        putStrLn $ "Result is : " ++ show r
    
    --my complicated func
    myFunc x y z = afunc x y z
    afunc x y z = bfunc x y
    bfunc x y = cfunc x
    cfunc x = do
        ret <- getRandomR (0.0,1.0)
        return ret
    

提交回复
热议问题