OCaml的最大整数值

9

我刚参加了一次面试,需要用到我提出的算法中的这个值。面试后,我很好奇是否真的有办法获得最大整数值。

我知道Int32.max_int和Int64.max_int。

但是当我将Int32.max_int的值设置为int时,它超过了Int可以拥有的最大值。

# Int32.max_int;;
- : int32 = 2147483647l
# let a: int = 21474836471;;
Characters 13-24:
  let a: int = 21474836471;;
               ^^^^^^^^^^^
Error: Integer literal exceeds the range of representable integers of type int

发现Int32.max_int末尾有一个l。感觉糟糕啊。 - louis1204
2个回答

12
$ ocaml
        OCaml version 4.01.0

# max_int;;
- : int = 4611686018427387903
# let a : int = max_int;;
val a : int = 4611686018427387903

更新

如果你使用的是32位系统,在纠正将末尾的L(l)误认为是1的错误后,Int32.max_int仍无法适应int类型。

# Int32.max_int;;
- : int32 = 2147483647l
# let i : int = 21474836471 (* Mistake *);;
Characters 14-25:
  let i : int = 21474836471 (* Mistake *);;
                ^^^^^^^^^^^
Error: Integer literal exceeds the range of representable integers of type int
# let i : int = 2147483647 (* No mistake *);;
Characters 14-24:
  let i : int = 2147483647 (* No mistake *);;
                ^^^^^^^^^^
Error: Integer literal exceeds the range of representable integers of type int
# 

所以我会说 L 不是问题所在。


谢谢您的快速回复!是的,这正是我在寻找的 :) - louis1204

3

请注意,在OCaml中,整数的最高位用于其自身的目的。

因此,int类型总是比机器本机类型少一位。Int32和Int64模块用于需要相应完整整数长度的应用程序,特别是与C库和函数的接口。

顶层测试:

# max_int;;        (* on 64 bit system *)
- : int = 4611686018427387903
# Int64.max_int;;  (* the lower case l is uppercase on my system *)
- : int64 = 9223372036854775807L
# let n = 9223372036854775807L;; (* correct type inference *)
val n : int64 = 9223372036854775807L

希望这有助于理解它。

1
OCaml 使用低位比特而不是高位比特。 - Jeffrey Scofield
@JeffreyScofield 考虑一下,最好不要动符号位。 - Str.
2
OCaml的实现在选择经济性方面令人印象深刻。使用低位非常适合区分立即值,因为指针几乎从不指向奇地址。而且算术运算相当容易;例如,对于加法,只需多执行一条指令来清除其中一个操作数的低位即可。 - Jeffrey Scofield

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接