Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use MonadRandom?

Tags:

haskell

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

like image 885
Andriy Drozdyuk Avatar asked Feb 13 '12 19:02

Andriy Drozdyuk


1 Answers

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
like image 122
porges Avatar answered Sep 22 '22 06:09

porges