[Haskell-beginners] state and randomness, Rand, RandT

Brent Yorgey byorgey at seas.upenn.edu
Sat Dec 11 03:45:34 CET 2010


On Sat, Dec 11, 2010 at 01:48:36AM +0000, Amy de Buitléir wrote:
> 
> And I'd really like to try using RandT, because this seems like the
> right situation for it. This compiles just fine.
> 
> pushRandom3 :: (RandomGen g) => RandT g (State Stack) ()
> pushRandom3 = do
>   xs <- get
>   r <- getRandomR (1,100)
>   put (r:xs)

Indeed, this is the right way to do it!

> 
> But I don't know if it works, because I can't figure out the magic
> incantation to get it to run!

Let's look at the type of evalRandT:

*Main Control.Monad.Random> :t evalRandT
evalRandT :: (Monad m, RandomGen g) => RandT g m a -> g -> m a

So we have:

*Main Control.Monad.Random> :t evalRandT pushRandom3 
evalRandT pushRandom3 :: (RandomGen g) => g -> State Stack ()

Let's pass it a generator:

*Main Control.Monad.Random> :t evalRandT pushRandom3 (mkStdGen 0)
evalRandT pushRandom3 (mkStdGen 0) :: State Stack ()

(Note, if you use mkStdGen 0 you will get the same random numbers
every time you run your program; instead you could use getStdGen to
get one based on the system clock or something like that.)
  
Now we have a State computation, so let's run it:

*Main Control.Monad.Random> :t execState (evalRandT pushRandom3 (mkStdGen 0))
execState (evalRandT pushRandom3 (mkStdGen 0)) :: Stack -> Stack
*Main Control.Monad.Random> :t execState (evalRandT pushRandom3 (mkStdGen 0)) [1,2,3,4,5]
execState (evalRandT pushRandom3 (mkStdGen 0)) [1,2,3,4,5] :: Stack

-Brent



More information about the Beginners mailing list