lundi 30 septembre 2019

How can I generate random numbers in Haskell without IO in a range?

I would like to generate random numbers in a range and the type signature to be Int -> Int. I've read multiple other posts but none of them suggested ways to return a type Int. I used System.IO.Unsafe in my code but it is not recommended to do so. Here's my code:

import System.IO.Unsafe

-- random number generator
rng :: Int -> Int
rng upper = unsafePerformIO $ randomRIO (0,upper-1) 

Does anyone have any suggests on how to generate random Int in a range in Haskell?

Edit: It might be impossible to change IO Int -> Int so I converted my code to

-- random number generator
rng :: Int -> IO Int
rng upper = randomRIO (0,upper-1) 

The reason why I need a rng is because I want to get random numbers within the range length of the list to get an index for an element of a list.

list !! rng (length list) but I'm getting the error Couldn't match expected type ‘Int’ with actual type ‘IO Int’ which is expected.

I'm new to Haskell and I don't know how to manipulate Monads. Any help is appreciated.




Aucun commentaire:

Enregistrer un commentaire