我已经阅读了有关 F# 中值限制的所有内容,但我仍然不明白。我有以下代码:
type tree<'a> =
| Nil
| Node of (tree<'a> * 'a * tree<'a>)
let rec flatten = function
| Nil -> []
| Node ( Nil, b, Nil ) -> [b]
| Node ( l, h, p ) -> List.concat [(flatten l);[h];(flatten p)]
并且编译器显示错误:
error FS0030: Value restriction. The value 'it' has been inferred to have generic type
val it : '_a list
Either define 'it' as a simple data term, make it a function with explicit arguments or, if you do not intend for it to be generic, add a type annotation.
谁能帮我?非常感谢你;)
最佳答案
请允许我使用我的通灵调试技能。您不能调用 flatten Nil
因为,正如编译器所指出的,结果可能是 'a list
对于任何类型'a
.您必须添加类型注释,例如 (flatten Nil : int list)
.
在不相关的说明中,您在 flatten 定义中的第二种情况是不必要的,可以删除,因为它也包含在第三种情况下。
关于F# 值限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4072167/