[Haskell-beginners] MonadRandom or Control.Monad.Random

Brent Yorgey byorgey at seas.upenn.edu
Sat Aug 1 13:36:39 EDT 2009


On Sat, Aug 01, 2009 at 10:17:20AM -0700, Michael Mossey wrote:
>
>
> Brent Yorgey wrote:
>> On Fri, Jul 31, 2009 at 05:55:43PM -0700, Michael P Mossey wrote:
>
>>> I'm looking at this example from the docs. I understand most of this but 
>>> I can't find a definition of getRandomR. See die has type (Rand g Int) 
>>> I'm assuming getRandomR is a function that has that type, but I can't 
>>> find its definition.
>>
>> getRandomR has type 
>>   (MonadRandom m, Random a) => (a, a) -> m a
>>
>> which in particular can be specialized to 
>>   (RandomGen g) => (Int,Int) -> Rand g Int . 
>> The documentation for getRandomR, and the other methods of the
>> MonadRandom class, can be found here:
>>
>>   http://hackage.haskell.org/packages/archive/MonadRandom/0.1.3/doc/html/Control-Monad-Random-Class.html
>
> Thanks. I'm still getting used to Haskell documentation. I was looking in 
> Control.Monad.Random, but I needed to look in Control.Monad.Random.Class.
>
> So I would like to know how to do something which is on the surface 
> imperative-like: toss a die until a 1 comes up, and count the number of 
> tosses. This would involve some kind of looping with an exit condition in 
> an imperative language. Can someone show me how to write that in Haskell?
>
> (Actually I want to do a lot more than that, but I just want to start there.)

You could do something as simple as this:

  tossesUntilOne :: (RandomGen g) => Rand g Int
  tossesUntilOne = do
    tosses <- getRandomRs (1,6)
    return $ length (takeWhile (/= 1) tosses) + 1

That is, instead of writing it as a loop with an exit condition, you
can just generate an infinite list of tosses, then count the length of
the portion before the first 1.

-Brent


More information about the Beginners mailing list