sml - 如何强制 SML 中的类型(如转换)

标签 sml smlnj

我正在创建 Rationals (int * int) 的结构,我的功能之一是:

fun diff ((n, d), (n', d')) = 
  let 
    val (top, bot) = sum ((n, d), (~n', d'))
  in 
    (top / gcd(top, bot), bot / gcd(top, bot))
  end

gcd 给出了最大公分母,所以我最终没有得到 2/8,而是应该得到的 1/4。 gcd 使用 mod 找到 gcd,因此它返回一个 int。但我无法将带除法的表达式输入为 int。当我尝试将 : int * int 添加到 diff 声明的末尾时,它给我一个类型错误,表达式 real * realint * int 不匹配。

如何强制整数除法,或将表达式转换为整数?如果两者都可以,哪个更好?

最佳答案

是的,您使用了错误的运算符。 / 是浮点除法运算符。 div(如 D.Shawley 所述)是整数除法运算符。 div 在这种情况下是正确的选择,因为您要除以两个整数并希望得到一个整数。

关于sml - 如何强制 SML 中的类型(如转换),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/745905/

相关文章:

string - 在 smlnj 中,您如何将 "string option"转换为 "string"?

sml - 标准 ML 类型中的问号意味着什么?

list - SML - 多项式的系数相乘

sml - 将值过滤到两个列表中

sml - 在不隐藏构造函数的情况下防止 SML 类型变为 eqtype

unit-testing - 具有多种结构的 SML 签名

sml - 查询 SML/NJ REPL 的签名或结构?

list - 从列表中获取元素的机制

algorithm - 有没有办法使用 Foldr 或 Foldl 函数在 SML 中编写堆排序算法?