[Haskell-beginners] Combining the Rand and State monads

Brent Yorgey byorgey at seas.upenn.edu
Thu Apr 5 19:52:47 CEST 2012


On Thu, Apr 05, 2012 at 10:42:20AM +0000, Amy de Buitléir wrote:
> I'm trying to develop a very simple simulation framework. A simulation consists
> of a list of models. Models generate output events based on an input event. Here
> is what I have currently (it works fine).
> 
> 
> modelT :: Model g
> modelT _ = do
>   s <- get
>   put $ s ++ " R"
>   n <- HOW DO I GET A RANDOM NUMBER????
>   return [n]

I assume you are using the MonadRandom package?  Getting a random
number is as simple as doing something like "getRandomR ('A','Z')" (or
using any other method from the MonadRandom class [1]).  There is an
instance MonadRandom m => MonadRandom (StateT s m), so calls to
getRandom, getRandomR, etc. are automatically lifted into your Model
monad.

Your problem seems to be the type you have given to modelT: it claims
that it will work for *any* type g but this is not so; g must
represent a pseudorandom number generator.  This works:

modelT :: RandomGen g => Model g
modelT _ = do
  s <- get
  put $ s ++ " R"
  n <- getRandomR ('A', 'Z')
  return [n]

-Brent

[1] http://hackage.haskell.org/packages/archive/MonadRandom/0.1.6/doc/html/Control-Monad-Random-Class.html



More information about the Beginners mailing list