如何使用MonadRandom? [英] How to use MonadRandom?
本文介绍了如何使用MonadRandom?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
目前我有一些代码可以完成像传递生成器变量一样的东西,全部从主函数的方式:
main = do
g< - getStdGen
r< - myFunc g
putStrLn结果是:++ show r
- my complex func
myFunc gxyz = afunc gxyz
afunc gxyz = bfunc gxy
bfunc gxy = cfunc gx
cfunc gx = ret其中
(ret,_)= randomR(0.0,1.0)g
谢谢
解决方案
基本上所有额外的 g
参数可以被删除。然后使用 Control.Monad.Random (例如 getRandomR
)。这里是你的例子(我添加了一些参数让它编译):
import Control.Monad.Random
main = do
g< - getStdGen
let r = evalRand(myFunc 1 2 3)g :: Double
- 或者如果你想做更多随机的东西,可以使用runRand:
- let(r,g')= runRand(myFunc 1 2 3)g ::(Double,StdGen)
putStrLn $结果是:++ show r
--my complex func
myFunc xyz = afunc xyz
afunc xyz = bfunc xy
bfunc xy = cfunc x
cfunc x = do
ret < - getRandomR(0.0,1.0)
return ret
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 way from the main function:
main = do
g <- getStdGen
r <- myFunc g
putStrLn "Result is : " ++ show r
--my complicated func
myFunc g x y z = afunc g x y z
afunc g x y z = bfunc g x y
bfunc g x y = cfunc g x
cfunc g x = ret where
(ret, _ ) = randomR (0.0, 1.0) g
Thanks
解决方案
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
这篇关于如何使用MonadRandom?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文