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
donotation and recursive functions usingIO:you should note the following:
n == 0the function will usereturnto wrap the empty list intoIOand return thisdobody it will first generate a random numberrusingrandomRIOn-1element list of random numbers usingrandomList (n-1)and bind it torsreturnagain to wrapr:rs(anelement list) intoIOand 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 Intthere 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
replicateMinControl.Monad- with this import the function simplifies to:fun fact internally this is implemented exactly as what JP answered ;)