[Int]的总和导致溢出 [英] Sum of [Int] causes overflow
本文介绍了[Int]的总和导致溢出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个返回[Int]
的函数,我想取列表的总和.但是,尽管每个元素都小于maxBound::Int
,但总和肯定更大.
I have a function that returns [Int]
and I would like to take the sum of the list. However, while each individual element is smaller than maxBound::Int
, the sum is definitely larger.
(人为)示例:
ghci> sum ([1..10000000] :: [Int])
-2004260032
是否有任何方法可以迫使总和累积到Integer
而不是Int
中?我在想这个错误吗?
Is there any way to force sum to accumulate into an Integer
instead of an Int
? Am I thinking about this wrong?
推荐答案
sum返回与其输入列表元素相同的类型:
sum returns the same type as its input list elements:
sum :: Num a => [a] -> a
,因此您需要将其传递给[Integer]
才能返回Integer
.如果您的输入列表已经是[Int]
类型,则可以使用以下功能:
so you need to pass it a [Integer]
in order to return an Integer
. If your input list is already of type [Int]
, you can use the function:
sum . map fromIntegral
相反:
ghci> sum . map fromIntegral $ ([1..10000000] :: [Int])
50000005000000
这篇关于[Int]的总和导致溢出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文