September 23, 2012
MonadRandom package is a random number generation monad. It is now available in Fedora. Install it using:
$ sudo yum install ghc-MonadRandom-devel
The example of simulating a die is shown below:
import Control.Monad.Random
die :: (RandomGen g) => Rand g Int
die = getRandomR (1,6)
dice :: (RandomGen g) => Int -> Rand g [Int]
dice n = sequence (replicate n die)
main = do
values <- evalRandIO (dice 1)
putStrLn (show values)
Compile it using:
$ ghc --make die.hs
[1 of 1] Compiling Main ( die.hs, die.o )
Linking die ...
You can run it using:
$ ./die
[3]
$ ./die
[5]
$ ./die
[1]
$ ./die
[1]
$ ./die
[6]
The fromList function produces a random value from a weighted list:
Prelude> :m + Control.Monad.Random
Prelude Control.Monad.Random> fromList [(1,2), (3,4), (5,6)]
5
Prelude Control.Monad.Random> fromList [(1,2), (3,4), (5,6)]
1
Prelude Control.Monad.Random> fromList [(1,2), (3,4), (5,6)]
5
Prelude Control.Monad.Random> fromList [(1,2), (3,4), (5,6)]
3
Prelude Control.Monad.Random> fromList [(1,2), (3,4), (5,6)]
1