Haskell 随机数生成

发布于 2024-11-30 06:31:30 字数 105 浏览 1 评论 0原文

在 Haskell 中处理随机数生成的最佳方法是什么(或者有什么权衡)?

我还没有看到真正权威的答案。

考虑:尽量减少对纯函数的影响、如何/何时播种、性能、线程安全

What's the best way to handle random number generation in Haskell (or what are the tradeoffs)?

I haven't really seen an authoritative answer.

Consider: minimizing the impact on otherwise pure functions, how / when to seed, performance, thread safety

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

北城挽邺 2024-12-07 06:31:30

恕我直言,最好的想法是将生成器保持在 严格状态记录。然后您可以使用普通的 do 语法来使用生成器。播种仅完成一次 - 在主程序开始时(或在每个线程开始时)。您可以通过使用 split 操作来避免 IO,该操作会从一个随机生成器中生成两个随机生成器。 (当然不同)。

由于状态仍然是纯粹的,因此可以保证线程安全。此外,您始终可以通过为函数提供随机生成器来转义状态。例如,这在自动单元测试的情况下很有用。

IMHO, the best idea is to keep the generator in a strict state record. Then you can use the ordinary do-Syntax to work with the generator. Seeding is done only once - at the beginning of the main program (or at the beginning of each thread). You can avoid IO by using the split operation, which yields two random generators from one. (Different, of course).

As state is still pure, threadsafety can be guaranteed. Additionally, you can always escape state by giving a random generator to the function. This is useful for instance in case of automatic unit tests.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文