Haskell大量骰子滚动的平均值

编程入门 行业动态 更新时间:2024-10-28 16:27:00
本文介绍了Haskell大量骰子滚动的平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

为了更好地学习Haskell,我正在尝试编写一个程序,该程序显示2个骰子的总和的平均值,滚动X次.在C,Java,Python中,这相当简单……但是我陷入了Haskell的困境.这是一个幼稚的尝试:

In an attempt to learn Haskell better, I'm trying to write a program that displays the average value of the sum of 2 die, rolled X number of times. This is fairly simple in C, Java, Python... but I'm stuck in Haskell. Here's a naive attempt:

import System.Random main = do g <- getStdGen let trials = 10000000 let rolls = take trials (randomRs (2, 12) g :: [Int]) let average = div (sum rolls) trials print average

对于少量试用,该程序有效.但是,当我通过一千万次试用运行此代码时,我得到一个错误:

For low number of trials, the program works. But when I run this code with ten million trials, I get an error:

Stack space overflow: current size 8388608 bytes. Use `+RTS -Ksize -RTS' to increase it.

必须有一个更好的方法来编写此程序.在C,Java和Python版本中,这是一个简单的任务.我看过此帖子(了解其中的75%材料),但是当我使该代码适应这种情况时,对R [Int]的序列求和是行不通的(而且我不确定如何解开" [Int]).我究竟做错了什么?正确的方法是什么?如何在Haskell中达到随机数启发?

There's got to be a better way to write this program. In the C, Java, and Python versions, this is a simple task. I've looked at this post (and understand about 75% of the material), but when I adapt that code to this situation, summing a sequence of R [Int] doesn't work (and I'm not sure how to 'unwrap' the [Int]). What am I doing wrong? What's the right way? How do I reach random number enlightenment in Haskell?

编辑:除了选择的答案外,正如rtperson指出的那样,两个骰子的建模不正确;它实际上应该是从1到6的两个独立掷骰的总和.

in addition to the answer selected, as rtperson points out below, the modeling of 2 dice is incorrect; it should really be the sum of two independent rolls from 1 to 6.

推荐答案

sum总结长列表是不好的,它在线性空间中运行.尝试使用sum的严格版本:

sum is no good to sum a long list, it runs in linear space. Try this strict version of sum:

sum' = foldl' (+) 0

foldl'在Data.List中定义.

编辑有关更多信息,请参见此HaskellWiki文章.

EDIT More information can be found in this HaskellWiki article.

更多推荐

Haskell大量骰子滚动的平均值

本文发布于:2023-10-30 13:42:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1543025.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:骰子   平均值   Haskell

发布评论

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

>www.elefans.com

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