i need to take one random element from a set of int. I am trying to use the function elemAt :: Int->Set a->a
but i need to randomly generate the Int which will be used in the first argument of elemAt
, but i am having a problem because randomRIO is a monadic function. How can i use randomRIO in a funcion that returns an int?Eg:
function :: Int->Int
function i = x <- randomRIO(0,i-1)
What i am trying to do is something like this:
element set = elemAt (function (size set)) set
In Haskell we want to know if our functions are pure - in your case you want to implement a function which is obviously not pure at all - it's random.
So you should be honest about this function and indicate this in the type. Now of course you can use randomRIO
and in this case you indicate this by returning IO
-computations.
Assuming you want to take random elements form Data.Set
s it could look like this:
randomElement :: Set a -> IO a
randomElement set = do
i <- randomRIO (0, size set - 1)
return $ set `elemAt` i
for Map
s, etc. it's similar
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.