[Haskell-cafe] Convert IO Int to Int
Krzysztof Skrzętnicki
gtener at gmail.com
Tue Jun 9 12:04:49 EDT 2009
On Tue, Jun 9, 2009 at 16:14, Daniel Fischer<daniel.is.fischer at web.de> wrote:
> Am Dienstag 09 Juni 2009 15:57:24 schrieb Magnus Therning:
>> On Tue, Jun 9, 2009 at 2:52 PM, ptrash<ptrash at web.de> wrote:
>> > Hmm...it am not getting through it. I just want to generate a random
>> > number and then compare it with other numbers. Something like
>> >
>> > r = randomRIO (1, 10)
>> > if (r > 5) then... else ...
>>
>> You have to do it inside the IO monad, something like
>>
>> myFunc = do
>> r <- randomRIO (1, 10
>> if r > 5
>> then ...
>> else ...
>>
>> /M
>
> Or make the source of the pseudo-random numbers explicit:
>
> import System.Random
>
> function :: (RandomGen g, Random a) => g -> other args -> result
> function gen whatever
> | r > 5 = blah newgen something
> | r < 3 = blub newgen somethingElse
> | otherwise = bling
> where
> (r,newgen) = randomR (lo,hi) gen
>
> and finally, when the programme is run:
>
> main = do
> args <- getArgs
> sg <- getStdGen
> foo <- thisNThat
> print $ function sg foo
>
> 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
> 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
More information about the Haskell-Cafe
mailing list