我似乎找不到关于为什么这不起作用的引用:
- (2000,1)<(2000,1);
stdIn:18.1-18.18 Error: operator and operand don't agree [overload]
operator domain: 'Z * 'Z
operand: (int * int) * (int * int)
in expression:
(2000,1) < (2000,1)
标准 ML 是否支持结构比较?
最佳答案
简短的回答:只为了平等。
顶层环境中的严格小于运算符 (<) 与其他比较运算符一样有点“特殊”。它们是“特殊的”,因为它们(作为唯一的)重载以处理整数、实数等。此外,这种重载的一些特殊之处在于,如果无法推断类型,则使用整数(例如,推断出多态类型 'a
)。
对于整数的情况 Int.<
使用函数,它只接受两个整数作为参数
- Int.<;
val it = fn : int * int -> bool
但是对于相等,情况有点不同,从相等运算符的类型可以看出
- op=;
val it = fn : ''a * ''a -> bool
这里的多态类型是蜜蜂''a
,请注意双 plings。这是因为它只能实例化为相等类型(例如,int、string、int'string 等)。请注意,real 不是相等类型!
更新
我通常做的事情是为我创建的每个(数据)类型创建一个比较函数。这样我就可以完全控制发生的事情。比较函数的想法是返回一个 order。
datatype order = LESS | EQUAL | GREATER
有了它,您可以轻松地创建 case 表达式并执行适当的操作,而不是 if .. < .. then .. else ..
更新1
以下代码来自 Andreas Rossberg 的评论。为了便于阅读,我把它放在这里
fun comparePair compareA compareB ((a1, b1), (a2, b2)) =
case compareA (a1, a2) of
EQUAL => compareB (b1, b2)
| other => other
以及一些使用示例
- comparePair Int.compare String.compare ((2, "foo"), (3, "bar"));
val it = LESS : order
- comparePair Int.compare String.compare ((3, "bar"), (3, "bar"));
val it = EQUAL : order
关于sml - 标准 ML 中的结构比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14407209/