在Haskell中生成一个范围内的随机整数

编程入门 行业动态 更新时间:2024-10-07 06:46:17
本文介绍了在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中生成一个范围内的随机整数

本文发布于:2023-11-29 02:21:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1644913.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:范围内   整数   Haskell

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!