如何在 SML 中反转自定义列表?

How to reverse a custom list in SML?

我的自定义数据类型定义如下:数据类型'a mylist = NIL | CONS of 'a * 'a mylist;

已经尝试了几个小时,但无法弄清楚如何反转这样的列表。

我的代码不起作用:

fun reverse NIL = NIL
| reverse (CONS(head,tail)) = reverse tail @ [head];

函数调用如下:

reverse (CONS(4,CONS(3,CONS(2,NIL))));

您不能将内置追加 (@) 和列表 ([head]) 与您自己的列表类型一起使用。

你需要CONS (head, NIL)而不是[head],你需要自己写

append: 'a mylist -> 'a mylist -> 'a mylist

append: ('a mylist * 'a mylist) -> 'a mylist

作为练习实施 append

使用追加运算符会增加该解决方案的时间复杂度。我会改为使用辅助函数来执行尾递归调用,从而以类似堆栈的方式反转列表。

例如

fun reverse xs =
let
  fun revhelp NIL ys = ys
    | revhelp (CONS(x,xs)) ys = revhelp xs (CONS(x,ys))
in
  revhelp xs NIL
end;