[英]Create Random number out of certain list in Haskell
I know that Haskell provides a function for producing a random number between a certain range. 我知道Haskell提供了用于在一定范围内产生随机数的功能。
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. 示例:假设存在
[1, 6, 9]
1,6,9]列表,并且我希望随机数不在此列表中,即1或6或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
). 也许最直接的方法是:1)获取
0
和length list - 1
之间的随机数length list - 1
2)使用该数字索引列表( list !! rand
)。
For example, if you are OK with living in the IO monad for your random numbers then you could use randomRIO
: 例如,如果您可以将IO放在随机数的IO monad中,那么可以使用
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.