在Haskell范围内生成无种子的随机整数 [英] Generate a random integer in a range in Haskell without a seed
问题描述
如何在不使用任何种子的情况下从范围(a,b)中在Haskell中生成随机数?
How can I generate a random number in Haskell from a range (a, b) without using any seed?
该函数应该返回一个Int而不是一个IO Int. 我有一个函数X,它带有Int和其他参数,并输出不是IO的东西.
The function should return an Int and not an IO Int. I have a function X that takes and Int and other arguments and outputs something which is not an IO.
如果这不可能,那么如何使用时间库生成种子并使用mkStdGen生成范围内的随机数?
If this is not possible, how can I generate a seed using the Time library and the generate a random number in the range with the mkStdGen ?
任何帮助将不胜感激.
推荐答案
一个函数不能在没有IO
的情况下返回Int
,除非它是一个纯函数,即给定相同的输入,您将始终获得相同的输出.这意味着,如果您想要一个不带IO
的随机数,则将需要一个种子作为参数.
A function cannot return an Int
without IO
, unless it is a pure function, i.e. given the same input you will always get the same output. This means that if you want a random number without IO
, you will need to take a seed as an argument.
-
如果选择获取种子,则种子的类型应为
StdGen
,并且可以使用randomR
从中生成数字.使用newStdGen
创建一个新种子(这必须在IO
中完成).
If you choose to take a seed, it should be of type
StdGen
, and you can userandomR
to generate a number from it. UsenewStdGen
to create a new seed (this will have to be done inIO
).
> import System.Random
> g <- newStdGen
> randomR (1, 10) g
(1,1012529354 2147442707)
randomR
的结果是一个元组,其中第一个元素是随机值,第二个是用于生成更多值的新种子.
The result of randomR
is a tuple where the first element is the random value, and the second is a new seed to use for generating more values.
否则,您可以使用randomRIO
直接在IO
monad中获取一个随机数,并为您提供所有StdGen
内容:
Otherwise, you can use randomRIO
to get a random number directly in the IO
monad, with all the StdGen
stuff taken care of for you:
> import System.Random
> randomRIO (1, 10)
6
这篇关于在Haskell范围内生成无种子的随机整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!