Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

[Haskell] help -- need a random number

0 views
Skip to first unread message

robert bauer

unread,
Apr 26, 2007, 12:58:26 PM4/26/07
to has...@haskell.org
Hi,

I need some random numbers. The documentation identifies StdGen, but I can't figure out how to invoke it. The documentation is great
in every way, except an actual example that I can essentially cut and paste.

Thanks

_______________________________________________
Haskell mailing list
Has...@haskell.org
http://www.haskell.org/mailman/listinfo/haskell

Johannes Waldmann

unread,
Apr 26, 2007, 1:07:08 PM4/26/07
to robert bauer

> I need some random numbers.

in the IO Monad, hiding the use of a generator

do x <- randomRIO (0, 1 :: Double) ; print x

you can also make the state explicit:

do g0 <- getStdGen ; let { ( x, g1 ) = randomR ( 0, 1::Double) g0 } ;
print x

a RandomGen is actually the state object for the generator,
much like http://java.sun.com/javase/6/docs/api/java/util/Random.html

best regards, J.W.

Marc A. Ziegert

unread,
Apr 26, 2007, 2:11:54 PM4/26/07
to robert bauer
module Dice where

import System.Random
import System.IO.Unsafe (unsafePerformIO,unsafeInterleaveIO)
import Data.List (unfoldr)

dice4,dice6,dice8,dice10,dice12,dice20,dice666 :: [Int]
dice4 = randomRs (1,4) (read "foo"::StdGen)
dice6 = randomRs (1,6) (mkStdGen 5)
dice8 = randomRs (1,8) (unsafePerformIO newStdGen)
dice10 = unfoldr (Just . randomR (1,10)) (read "42"::StdGen)
dice12 = fmap ((+1).(mod `flip` 12)) $ randoms (read "bar"::StdGen)
dice20 = [succ $ x `mod` 20|x<-unfoldr (Just . random) (mkStdGen 23)]
dice666 = unfoldr (\io_a -> Just . unsafePerformIO $ fmap ((,)`flip` io_a) io_a) $ randomRIO (1,666)

Johannes Waldmann

unread,
Apr 26, 2007, 2:16:05 PM4/26/07
to Marc A. Ziegert

> import System.IO.Unsafe (unsafePerformIO,unsafeInterleaveIO)

Whoa! I'd be very cautious recommending these for newbies ...

Marc A. Ziegert

unread,
Apr 26, 2007, 3:06:42 PM4/26/07
to has...@haskell.org
that is exact the way, how i had learned about the state monads like IO and Maybe.
that was even before i understood the [] monad, folding and using Random; i don't remember when that was... ghc-5.xx age.

in my opinion, unsafePerformIO is a good learning tool, as soon as you use it tricky to analyze and discover "new worlds you have never been before".
like this:

blah = unsafePerformIO $ do
putStrLn "I'm here: blah!"
return blub

this way, it may be even more important than undefined:

undef s = unsafePerformIO $ do
putStrLn "whops, this shouldn't happen"
putStrLn s
return undefined


well, this is my unpure way of learning to think in new languages.
i used ways like this in c++ to analyze OOP and to discover the world before and after int main().

greetings
- marc

0 new messages