2012-03-30 72 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子句的實現省略了,因爲您已將問題標記爲作業。