types - SML : Inputting an empty list into function gives error “Warning: type vars not generalized because of value restriction…”

标签 types compiler-errors ml

我的功能旨在将列表中的第一项放在列表的末尾。
该列表可以是任何类型。
我试图预期会有一个空列表输入,但是在类型方面却出现了错误。

如何使此代码按预期工作?

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

请注意,实际上有一个结果[],它是“虚拟类型” ?.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]

关于types - SML : Inputting an empty list into function gives error “Warning: type vars not generalized because of value restriction…” ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48793321/

相关文章:

c++ - 编译 SFML 2.0 项目时加载共享库时出错

c# - 将 T 限制为 int 值?

f# - 通过翻译 ML 的等效项来使用 F# 实现 take

scope - 标准 ML - 在 let-in-end 表达式中更新全局变量?

functional-programming - 模式匹配 SML?

c# - 将 XAML 窗口类型传递给函数

javascript - 如何在 Angular-2 中获取 Form Group 的值

java - 在除法之前将 int 类型转换为 float。我真正需要哪些类型转换,我可以删除哪些类型转换,为什么?

types - 为什么 Julia 的 Union 和 Tuple 实例是 DataType 而不是 UnionAll?

objective-c - 使用typedef枚举时,返回类型枚举EnumName返回枚举成员时会产生编译器错误