[Haskell-cafe] Convert IO Int to Int

Luke Palmer lrpalmer at gmail.com
Tue Jun 9 15:46:33 EDT 2009


2009/6/9 Krzysztof Skrzętnicki <gtener at gmail.com>

> On Tue, Jun 9, 2009 at 16:14, Daniel Fischer<daniel.is.fischer at web.de>
> wrote:
> > If you're doing much with random generators, wrap it in a State monad.
>
> To avoid reinventing the wheel one can use excellent package available
> on Hackage:
> http://hackage.haskell.org/cgi-bin/hackage-scripts/package/MonadRandom


Please do!  Prefer MonadRandom to explicit generator passing:
http://lukepalmer.wordpress.com/2009/01/17/use-monadrandom/.  Keep
computations in MonadRandom, and pull them out with evalRandomIO at the last
second.

Luke


> <http://hackage.haskell.org/cgi-bin/hackage-scripts/package/MonadRandom>
>
> > The die function simulates the roll of a die, picking a number between 1
> and 6, inclusive, and returning it in the Rand monad.
> > Notice that this code will work with any source of random numbers g.
> >
> > die :: (RandomGen g) => Rand g Int
> > die = getRandomR (1,6)
> >
> > The dice function uses replicate and sequence to simulate the roll of n
> dice.
> >
> > dice :: (RandomGen g) => Int -> Rand g [Int]
> > dice n = sequence (replicate n die)
> >
> > To extract a value from the Rand monad, we can can use evalRandIO.
> >
> > main = do
> >   values <- evalRandIO (dice 2)
> >   putStrLn (show values)
>
> Best regards
>
> Krzysztof Skrzętnicki
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20090609/9fd21e1b/attachment.html


More information about the Haskell-Cafe mailing list