SML:将空列表输入函数会出错 "Warning: type vars not generalized because of value restriction..."

SML: Inputting an empty list into function gives error "Warning: type vars not generalized because of value restriction..."

我的功能是将列表中的第一项放在列表末尾。 该列表可以是任何类型。 我试图预期一个空列表输入,但我收到有关类型的错误。

我该怎么做才能让这段代码按预期工作?

fun cycle1 aList = if null(aList) then []else tl(aList) @ [hd aList];
cycle1 [];

stdIn:24.1-24.10 Warning: type vars not generalized because of
   value restriction are instantiated to dummy types (X1,X2,...)

这不是错误,只是警告。

- fun cycle1 aList = if null(aList) then []else tl(aList) @ [hd aList];
val cycle1 = fn : 'a list -> 'a list
- cycle1 [];
stdIn:2.1-2.10 Warning: type vars not generalized because of
   value restriction are instantiated to dummy types (X1,X2,...)
val it = [] : ?.X1 list

请注意,实际上有一个结果 - [] - 这是 "dummy type"、?.X1 list 的列表。

发生这种情况是因为值不能是多态的(您不能创建 'a list)。
搜索 值限制 了解详细信息。

您可以使用特定类型的空列表来避免警告:

- cycle1 ([] :int list);
val it = [] : int list
- cycle1 ([] : string list);
val it = [] : string list

附带说明一下,我建议您尽快熟悉模式匹配,因为它使代码更具可读性;

fun cycle1 [] = []
  | cycle1 (x::xs) = xs @ [x]