SML : how to compare (< or >) two equality types

标签 sml

我在 SML 中遇到以下代码问题:

fun inter s1 s2 =
  let
    fun inter' [] _ interSet = interSet
      | inter' _ [] interSet = interSet 
      | inter' (x1::s1) (x2::s2) interSet =
            if x1=x2 then
                inter' s1 s2 (x1::interSet) (* Add the value to the intersection and advance in both s1 and s2*)
            else if x1 < x2 then
                inter' s1 (x2::s2) interSet (* Keep going through s1 *)
            else
                inter' (x1::s1) s2 interSet (* Keep going through s2 *)
   in
      if s1=[] orelse s2=[] then []
      else                          
        inter' s1 s2 []
end;

inter 函数返回一个列表,其中包含两个有序列表 s1 和 s2 之间的交集(即在 s1 和 s2 中找到的值)。我期望它适用于所有相等类型,但函数类型是:

val inter = fn: int list -> int list -> int list

为什么不是:

val inter = fn: ''a list -> ''a list -> ''a list    ?

看来问题出在

x1 < x2

我是否错误地认为 < 运算符对于所有相等类型都被重载了?例如,它不应该能够比较字符串吗?

最佳答案

是的,你的想法是错误的。如果相等类型支持排序,它们可能会被称为有序类型。 ;)

您需要做的是将比较运算符作为参数传递给 inter 函数。或者,如果这是更大模块的一部分,您可以考虑将其设为仿函数。在这两种情况下,我建议不要传递 less-then 运算符,而是传递一个 3 路函数 compare : 'a * 'a -> order,正如为每个内置类型预定义的那样,例如, Int.compare

关于SML : how to compare (< or >) two equality types,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46227727/

相关文章:

sml - SML 中嵌套 "if else"的语法

sml - 如何将 Real 转换为 Int?

sml - 在标准 ML 中,您如何捕获像 "Error: unbound variable or constructor: foo"这样的异常?

sml - infix、infixr、infixl 之间的区别

compiler-errors - 在模式中不带参数的数据构造函数?

sml - SML中的 'op'运算符

sml - 令人困惑的 SML 语句

operators - SML 选项 Monad(绑定(bind)运算符不起作用)

syntax-error - sml 中的语法错误 : Inserting LOCAL

使用foldr在SML中快速排序