Haskell大量骰子滚动的平均值 [英] Average of large number of Dice Rolls in Haskell

查看:66
本文介绍了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大量骰子滚动的平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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