【问题标题】:reverse function in mylist standard mlmylist 标准 ml 中的反向函数
【发布时间】:2012-10-04 21:31:45
【问题描述】:

我想创建一个反转自定义列表的函数,但它不起作用,我在上一个问题中被建议使用一个函数,但它使用了另一个函数,我想在没有任何外部函数的情况下使用它,我'我已经写了一些代码,我会很感激一些关于如何使它工作的提示。

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

代码有什么问题?

【问题讨论】:

    标签: list reverse sml


    【解决方案1】:

    您已经交换了列表的头部和尾部的顺序。你定义了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 子句的实现,因为您已将问题标记为作业。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-13
      • 2016-01-19
      • 2012-04-09
      • 1970-01-01
      • 2015-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多