2012-03-30 69 views
0

我想制作一个反转自定义列表的函数,但它不起作用,在前面的问题中,我已经提出了一个函数,但它使用了另一个函数,我希望不使用它任何外部功能,我已经写了一些代码,我希望有关如何使其工作的一些提示。mylist标准ml中的反向函数

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>)) 

什么是错的代码?

回答

2

您已切换列表的首尾顺序。您定义了CONS of 'element * 'element mylist,因此它应该用作CONS(head, tail)。您在reverse中将其用作CONS(tail, head)。因此,这两个条款表示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子句的实现省略了,因为您已将问题标记为作业。