SML/NJ Error: operator and operand don't agree

SML/NJ Error: operator and operand don't agree

我正在尝试在 SML/NJ 中编写函数 contains:

fun contains(el: 'a, items: 'a list) =
  if null items
  then false
  else ((hd items) = el) orelse contains(el, tl items)

我知道我可能可以使用本机 list 函数实现相同的最终结果,但这是针对要求不使用任何 SML/NJ 超出其涵盖的基础功能的 MOOC迄今。我得到的错误是:

solution.sml:10.9-10.24 Error: operator and operand don't agree [UBOUND match]
  operator domain: ''Z * ''Z
  operand:         'a * 'a
  in expression:
    hd items = el

我不是 100% 确定为什么我不能像在 'a list 中那样对 'a 进行抽象,我希望 'a 表示相同的抽象类型在这两种情况下。我做的完全错了吗?

在 ML 中,您通常无法比较泛型类型的值,例如 'a。但是,有一种特殊的泛型类型 ''a,它代表支持使用 = 运算符进行相等性测试的类型。

您实际上可以看到错误消息暗示了这一点,它说 ''Z * ''Z 与类型 'a * 'a 不匹配 - 您使用 'a 明确地将函数定义为通用函数,但是编译器希望它是允许比较的通用参数 ''Z

以下应该可以解决问题:

fun contains(el: ''a, items: ''a list) =
  if null items
  then false
  else ((hd items) = el) orelse contains(el, tl items)