为了更好地学习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' (+) 0foldl'在Data.List中定义.
编辑有关更多信息,请参见此HaskellWiki文章.
EDIT More information can be found in this HaskellWiki article.
更多推荐
Haskell大量骰子滚动的平均值
发布评论