首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SML代码错误

SML代码错误
EN

Stack Overflow用户
提问于 2017-09-13 12:38:47
回答 1查看 224关注 0票数 0

嗨,我在下面的SML代码中遇到了编译错误,有人能帮我吗?

代码语言:javascript
复制
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

代码:

代码语言:javascript
复制
 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]);
EN

回答 1

Stack Overflow用户

发布于 2017-09-13 20:49:39

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

SML还提供了类型推断,因此实际上不需要指定参数的类型(尽管它对调试很有用)。如果您确实想要指定类型,如molbdnilo所评论的,那么您要查找的类型是intint list,或者''a''a list ('' a是相等类型的类型变量)。

与此无关的是,也许编写函数的一种更常用的方法是通过对列表结构进行用例分析来定义它,而不是使用布尔检查。这样做的好处是,您可以立即获得支持对列表是否为空进行布尔检查的数据,而不是先检查然后再提取数据。例如:

代码语言:javascript
复制
fun exists_in (item, []) = false
  | exists_in (item, h::t) = (item = h) orelse exists_in (item, t)
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46188955

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档