【发布时间】:2017-10-12 10:35:01
【问题描述】:
我正在尝试编写一个简单的程序,用标准 ML 语言计算 x 的 17 次方。我应该通过“帮助程序”来做到这一点:
fun help (y:int) = y * y * y * y;
fun power17 (x:int) = help (help (help (help (x) ) ) ) * x;
这会导致溢出。谁能告诉我为什么会这样?
【问题讨论】:
标签: overflow sml exponentiation
我正在尝试编写一个简单的程序,用标准 ML 语言计算 x 的 17 次方。我应该通过“帮助程序”来做到这一点:
fun help (y:int) = y * y * y * y;
fun power17 (x:int) = help (help (help (help (x) ) ) ) * x;
这会导致溢出。谁能告诉我为什么会这样?
【问题讨论】:
标签: overflow sml exponentiation
你得到一个整数溢出。如果你想让你的代码工作,你需要使用LargeInt.int。
fun help (y: LargeInt.int) = y * y * y * y;
fun power17 (x: int) =
let
val x' = Int.toLarge x
in
help (help (help (help (x')))) * x'
end;
还有一件事,该代码不是在计算 x ** 17,而是在计算 x ** 257。
您应该只调用两次help:
fun power17 (x:int) = (help (help x)) * x;
【讨论】:
您的函数不计算 17 的幂。评估它:
power17 2 ~> help (help (help (help x))) * 2
~> help (help (help (2 * 2 * 2 * 2))) * 2 (* that's 2^5 *)
~> help (help (help (8))) * 2
~> help (help (8 * 8 * 8 * 8)) * 2 (* that's 2^13 *)
~> help (help (4096)) * 2
~> help (4096 * 4096 * 4096 * 4096) * 2 (* that's 2^49 *)
~> raise Overflow (* most SML compilers have 32-bit ints *)
也许你打算写:
fun power17 x = help x * help x * help x * help x * x
不过,这听起来像是递归的理想情况:
fun power (x, 0) = 1
| power (x, n) = x * power (x, n-1)
fun power17 x = power (x, 17)
【讨论】: