[英]What is the upper bound of Integer in Haskell?
I was solving a math problem: want to get the sum of the digits of the number 2^1000
. 我正在解决一个数学问题:想要获取数字
2^1000
的数字总和。
In Java, the solution is like: 在Java中,解决方案类似于:
String temp = BigInteger.ONE.shiftLeft(1000).toString();
int sum = 0;
for (int i = 0; i < temp.length(); i++)
sum += temp.charAt(i) - '0';
Then came up a solution in Haskell, like this: 然后在Haskell中提出一个解决方案,如下所示:
digitSum ::(Integral a) => a -> a
digitSum 0 = 0
digitSum n = (mod n 10) + (digitSum (div n 10))
The whole process is pretty smooth, one point seems interesting, we know integer type can not handle 2 ^ 1000
, too big, in Java, it's obvious to use BigInteger
and treat the big number to string, but in Haskell, no compiling errors means the 2 ^ 1000
could be passed in directly. 整个过程非常顺利,有一点似乎很有趣,我们知道整数类型不能处理
2 ^ 1000
,太大了,在Java中,使用BigInteger
并将大数字处理为字符串是显而易见的,但是在Haskell中,没有编译错误意味着2 ^ 1000
可以直接传递。 Here is the thing, does Haskell transform the number into string internally? 这是问题,Haskell是否在内部将数字转换为字符串? I want to make sure what the type is and let the compiler to determine, then I type the following lines in GHCi :
我想确定类型是什么,然后让编译器确定,然后在GHCi中键入以下几行:
Prelude> let i = 2 ^ 1000
Prelude> i
107150860718626732094842504906000181056140481170553360744375038837035105112493612249319
837881569585812759467291755314682518714528569231404359845775746985748039345677748242309
854210746050623711418779541821530464749835819412673987675591655439460770629145711964776
86542167660429831652624386837205668069376
Prelude> :t i
i :: Integer
Here, I was totally confused, apparently, the number of i
is oversized, but the return type of i
is still Integer
. 在这里,我完全感到困惑,显然,
i
的数量过大,但是i
的返回类型仍然是Integer
。 How could we explain this and what's the upper bound or limit of Integer
of Haskell? 我们该如何解释?Haskell
Integer
的上限或上限是多少?
In Haskell, Integer
is a - theoretically - unbounded integer type. 在Haskell中,
Integer
从理论上讲是无界的整数类型。 Fixed-width types are Int
, Int8
, Int16
, Int32
, Int64
and the corresponding unsigned Word
, Word8
etc. 固定宽度类型为
Int
, Int8
, Int16
, Int32
, Int64
以及相应的无符号Word
, Word8
等。
In practice, even Integer
is of course bounded, by the available memory for instance, or by the internal representation. 实际上,即使是
Integer
,当然也受可用内存或内部表示形式的限制。
By default, GHC uses the GMP package to represent Integer
, and that means the bound is 2^(2^37)
or so, since GMP uses a 32-bit integer to store the number of limbs. 默认情况下,GHC使用GMP包表示
Integer
,这意味着边界为2^(2^37)
左右,因为GMP使用32位整数存储肢体数。
Integer
has no upper bound in Haskell; 在Haskell中,
Integer
没有上限。 it is an unbounded integer type. 它是无界整数类型。
Integer
in Haskell is like BigInteger
in Java, and Integer
in Java is like Int
in Haskell. Haskell中的
Integer
类似于Java中的BigInteger
,而Java中的Integer
类似于Haskell中的Int
。 Int
in Haskell has it's bounds at [-2^63, 2^63). Haskell中的
Int
的边界为[-2 ^ 63,2 ^ 63)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.