标准ML中的结构比较

时间:2013-01-18 20:37:30

标签: sml ml comparison-operators

我似乎无法找到为什么这不起作用的参考:

- (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是否支持结构比较?

1 个答案:

答案 0 :(得分:5)

简短的回答:只是为了平等。

顶层环境中的严格小于运算符(&lt;)与其他比较运算符有点“特殊”。它们是“特殊的”,因为它们(作为唯一的)重载以使用整数,实数等。此重载的一些特殊之处是如果无法推断类型,则使用整数(例如,推断出多态类型'a)。

对于整数的情况,使用Int.<函数,它只需要两个整数作为参数

- Int.<;
val it = fn : int * int -> bool

但是对于相等,情况有点不同,正如等式运算符

的类型所示
- op=;
val it = fn : ''a * ''a -> bool

这里的多态类型被认为是蜜蜂''a,请注意双重刺激。这是因为它只能被实例化为相等类型(例如,int,string,int'string等)。请注意,real不是相等类型!

<强>更新

我通常做的是为我创建的每个(数据)类型创建一个比较函数。这样我就可以完全控制发生的事情。比较函数的想法是返回order

datatype order = LESS | EQUAL | GREATER

通过这种方式,您可以轻松地创建案例表达并执行相应的操作,而不是if .. < .. then .. else ..

<强> UPDATE1

以下代码来自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
相关问题