使用 SML 计算整数中的数字总和
Sum of digits in an integer using SML
我正在尝试创建一个函数来对 SML 中的整数数字求和,但出现以下错误。
Error: operator and operand don't agree [overload conflict]
operator domain: real * real
operand: [* ty] * [* ty]
in expression:
n / (d * 10)
我尝试将变量类型转换为真实变量,但没有成功。我也不明白为什么会出现此错误。不能在 SML 中将 * 和 / 等运算符与 int 和 real 一起使用吗?
代码如下:
fun sumDigits (n) =
if n < 10 then n
else
let
val d = 10
in
n mod d + sumDigits(trunc(n/(d*10)))
end
看起来你有几处不对。首先,在 dividing 整数时,您需要使用 "div" 而不是“/”。 / 是真实的。此外,trunc 是实数函数。第三,您希望递归逻辑只是 sumDigits(n div 10),而不是 sumDigits(n div (d*10))。您还可以通过删除 d 变量来清理代码。
fun sumDigits (n) =
if n < 10 then n
else
n mod 10 + sumDigits(n div 10)
我正在尝试创建一个函数来对 SML 中的整数数字求和,但出现以下错误。
Error: operator and operand don't agree [overload conflict]
operator domain: real * real
operand: [* ty] * [* ty]
in expression:
n / (d * 10)
我尝试将变量类型转换为真实变量,但没有成功。我也不明白为什么会出现此错误。不能在 SML 中将 * 和 / 等运算符与 int 和 real 一起使用吗?
代码如下:
fun sumDigits (n) =
if n < 10 then n
else
let
val d = 10
in
n mod d + sumDigits(trunc(n/(d*10)))
end
看起来你有几处不对。首先,在 dividing 整数时,您需要使用 "div" 而不是“/”。 / 是真实的。此外,trunc 是实数函数。第三,您希望递归逻辑只是 sumDigits(n div 10),而不是 sumDigits(n div (d*10))。您还可以通过删除 d 变量来清理代码。
fun sumDigits (n) =
if n < 10 then n
else
n mod 10 + sumDigits(n div 10)