【问题标题】:Error in SML codeSML 代码错误
【发布时间】:2018-02-21 15:47:58
【问题描述】:

您好,我在以下 SML 代码中遇到编译错误,有人可以帮忙吗?

Error: operator and operand don't agree [UBOUND match]
  operator domain: 'Z list
  operand:         ''list
  in expression:
    null mylist
stdIn:4.15-4.24 Error: operator and operand don't agree [UBOUND match]
  operator domain: 'Z list
  operand:         ''list
  in expression:
    hd mylist
stdIn:6.19-6.36 Error: operator and operand don't agree [UBOUND match]
  operator domain: 'Z list
  operand:         ''list
  in expression:
    tl mylist
stdIn:6.10-7.21 Error: operator is not a function [circularity]
  operator: 'Z

在表达式中: (exists_in (item,tl mylist)) exists_in

代码:

 fun exists_in (item: ''int, mylist:''list) =
        if null mylist
        then false
        else if  (hd mylist) = item 
        then true
        else exists_in(item, tl mylist)
    exists_in(1,[1,2,3]);

【问题讨论】:

  • 我认为您的意思是 intint list''a''a list,而不是 ''int''list

标签: sml smlnj


【解决方案1】:

每条错误消息都在告诉您,您正在将函数应用于错误类型的内容。例如,null'a list -> bool 类型,因此期望应用于 'a list 类型的参数。在exists_in 中,您将null 应用于第4 行的''list 类型。

SML 还提供类型推断,因此无需指定参数的类型(尽管它对调试很有用)。如果您确实想指定类型,正如 molbdnilo 评论的那样,您正在寻找的类型是 intint list,或 ''a''a list'' a 是相等类型的类型变量)。

不相关的是,编写函数的一种更惯用的方法可能是通过对列表结构的案例分析来定义它,而不是使用布尔检查。这样做的好处是您会立即获得支持布尔检查列表是否为空的数据,而不是检查然后提取数据。例如:

fun exists_in (item, []) = false
  | exists_in (item, h::t) = (item = h) orelse exists_in (item, t)

【讨论】:

    猜你喜欢
    • 2011-09-21
    • 1970-01-01
    • 2014-11-07
    • 2013-01-31
    • 2017-11-20
    • 1970-01-01
    • 1970-01-01
    • 2014-07-15
    • 2017-06-01
    相关资源
    最近更新 更多