我想创建一个反转自定义列表的函数,但它不起作用,我在前一个问题中被建议了一个函数,但它使用了另一个函数,我想在没有任何外部函数的情况下使用它,我'我写了一些代码,我会很感激如何使它成功。
datatype 'element mylist =
NIL
| CONS of 'element * 'element mylist;
fun reverse (CONS(x, NIL)) = CONS(NIL, x)
| reverse (CONS(x, xs)) = CONS((reverse xs), CONS(x, NIL));
我得到的错误是:
stdIn:89.5-90.60 Error: right-hand-side of clause doesn't agree with function result type [circularity]
expression: 'Z mylist mylist mylist
result type: 'Z mylist mylist
in declaration:
reverse =
(fn CONS (<pat>,<pat>) => CONS (<exp>,<exp>)
| CONS (<pat>,<pat>) => CONS (<exp>,<exp>))
代码有什么问题?
答案 0 :(得分:2)
您已切换列表头部和尾部的顺序。您定义了CONS of 'element * 'element mylist
,因此应将其用作CONS(head, tail)
。您在CONS(tail, head)
中将其用作reverse
。因此,这两个子句表示reverse
的矛盾类型,并且您得到错误。颠倒参数的顺序不足以将CONS
转换为append
函数。
您的反向函数应该有一个带有子句的表单,该子句遵循数据类型的构造函数。一种可能性是这样的:
fun reverse NIL = NIL
| reverse CONS(x, xs) = (* implementation for CONS *)
可能更容易添加用于构建结果的第二个参数。它应该是这样的:
fun reverse'(NIL, result) = result
| reverse'(CONS(x,xs), result) = (* implementation for CONS *)
并被称为reverse'(lst, NIL)
。
我遗漏了CONS
条款的实施,因为您已将问题标记为家庭作业。