I want to generate a list with random numbers in Haskell. I have to use the import System.Random library. I started doing something like that but it doesn't work. I have to create a list with N positions, and all these positions must have random numbers. Thanks!
System.Random library
import System.IO
x = randomRIO (1,6::Int)
test :: IO Int
test = randomRIO (1,6::Int)
While JP Moresmau solution is certainly preferable, you might be interested in a more transparent solution that shines some light on the
do
notation and recursive functions usingIO
:you should note the following:
n == 0
the function will usereturn
to wrap the empty list intoIO
and return thisdo
body it will first generate a random numberr
usingrandomRIO
n-1
element list of random numbers usingrandomList (n-1)
and bind it tors
return
again to wrapr:rs
(an
element list) intoIO
and return ithere is an example in GHCi:
seems random enough
remarks/exercise:
the function has a problem with certain values of
n
- can you spot it? And if so - can you change the function to be total?having some fun
If you look closely you see that you can pull out
randomRIO (1,6) :: IO Int
there like this:which of course you would have to use like this:
now this has been done before (in a slightly different/better) way and you can find it as
replicateM
inControl.Monad
- with this import the function simplifies to:fun fact internally this is implemented exactly as what JP answered ;)