在Haskell中生成一个范围内的随机整数 [英] Generate a random integer in a range in Haskell

查看:141
本文介绍了在Haskell中生成一个范围内的随机整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在不使用任何种子的情况下从范围(a,b)在Haskell中生成一个随机数?

函数应该返回一个Int而不是IO Int。
我有一个函数X,它接受Int和其他参数并输出不是IO的东西。



如果这不可行,我该如何生成一个使用时间库的种子,并在mkStdGen范围内生成一个随机数?



任何帮助都将得到真正的赞赏。


<如果没有 IO ,函数不能返回 Int ,除非它是一个纯函数,即给定相同的输入,你将始终得到相同的输出。这意味着如果你想要一个没有 IO 的随机数字,你将需要一个种子作为参数。




  • 如果您选择种子,它应该是 StdGen 类型,您可以使用 randomR 从它生成一个数字。使用 newStdGen 创建一个新的种子(这将必须在 IO 中完成)。

     > import System.Random 
    > g< - newStdGen
    > randomR(1,10)g
    (1,1012529354 2147442707)

    code> randomR 是一个元组,其中第一个元素是随机值,第二个元素是用于生成更多值的新种子。

  • $ b $否则,您可以使用 randomRIO 直接在 IO monad中获得一个随机数,与所有的 StdGen 的东西照顾你:

     > import System.Random 
    > randomRIO(1,10)
    6



How can I generate a random number in Haskell from a range (a, b) without using any seed?

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.

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 ?

Any help would be really appreciated.

解决方案

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.

  • If you choose to take a seed, it should be of type StdGen, and you can use randomR to generate a number from it. Use newStdGen to create a new seed (this will have to be done in IO).

    > import System.Random
    > g <- newStdGen
    > randomR (1, 10) g
    (1,1012529354 2147442707)
    

    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.

  • 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆