I know that Haskell provides a function for producing a random number between a certain range.
Is there a way of producing random number from a set of numbers ?
Example: Suppose list of [1, 6, 9]
exists and I want the random number to be out of this list ie 1 or 6 or 9.
Well there are certainly a lot of ways to accomplish this task. Perhaps the most straight forward is to 1) get a random number between 0
and length list - 1
2) Use that number to index the list ( list !! rand
).
For example, if you are OK with living in the IO monad for your random numbers then you could use randomRIO
:
import System.Random
oneOf :: [a] -> IO (Maybe a)
oneOf [] = return Nothing
oneOf list = do
rand <- randomRIO (0,length list - 1)
return (Just $ list !! rand)
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.