[Haskell-cafe] Convert IO Int to Int
Daniel Fischer
daniel.is.fischer at web.de
Tue Jun 9 10:14:44 EDT 2009
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.
More information about the Haskell-Cafe
mailing list