[Haskell-cafe] Generate 50 random coordinates

Donald Bruce Stewart dons at cse.unsw.edu.au
Sat Dec 2 02:31:20 EST 2006


hankgong:
> 
> Hello,all
> 
> My intention is to generate 50 random coordinates like (x,y).
> 
> myrand :: Int
> myrand = randomRIO(1::Int, 100)
> 
> rf=[(myrand, myrand) | a <- [1..50]]
> 
> My short program is like this. However, GHCI say that the return type of
> randomRIO is IO a while the function defined by me is Int. Since I only need
> a integral type as my cooridinate, could you tell me how to fix this?
> 

Try initialising your random generator in 'main' , creating a list of
infinite randoms, take the number you need, then feed that to the
functions that need the list:

    import System.Random
    import Text.Printf
    import Data.Word

    main = do
        g <- newStdGen          -- intialise a random generator
        let (a,b) = split g     -- create two separate generators
            as = randoms a      -- one infinite list of randoms
            bs = randoms b      -- another
            rs = zip as bs      -- an infite list of pairs
        dump (take 50 rs)       -- take 50, and consume them

    dump :: [(Int,Int)] -> IO ()
    dump s = mapM_ (uncurry (printf "(%d,%d)\n")) s

And running this:

    $ runhaskell A.hs
    (639240856,75173658)
    (-979753698,2004752008)
    (1514872498,-686799980)
    (1122012756,-645055058)
    ...

-- Don


More information about the Haskell-Cafe mailing list