F# 值限制

标签 f# value-restriction

我已经阅读了有关 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/

相关文章:

f# - 另一个值限制问题

f# - 了解 F# 值限制错误

polymorphism - 如何柯里化(Currying)带有可选参数的函数,以在 ReasionML/BuckleScript 中生成 Js.t 对象?

F# 编译器错误 FS0030,值限制问题

f# - Visual Studio 2013 预览版、Google Test Runner 无法加载文件或程序集 F#

memory-leaks - F# 可观察事件是否消除、调解或与弱引用的需要无关?

math - 有 F# 的数学库吗?

f# - 如何在函数式编程(F#)中将行号添加到文本文件?

F# 和运算符重载 : (>) and (^)