【问题标题】:F# value restrictionF# 值限制
【发布时间】:2011-05-03 14:21:00
【问题描述】:

我已经阅读了有关 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?我可以很好地编译和运行这个示例
  • 但是当我调用 flatten Nill;;有问题。

标签: f# value-restriction


【解决方案1】:

请允许我使用我的通灵调试技能。您不能调用flatten Nil,因为正如编译器所指出的,对于任何类型'a,结果可能是'a list。必须添加类型注解,例如(flatten Nil : int list)

在不相关的说明中,您在 flatten 定义中的第二种情况是不必要的,可以删除,因为它也被第三种情况所涵盖。

【讨论】:

  • 至于“flatten定义中的第二种情况是不必要的,可以删除,因为它也被第三种情况所涵盖”的无关注释,第二种情况的性能是否会更好,因为它会减少很多额外的匹配项?
  • @dc7a9163d9 - 是的,这当然是可能的。但我会默认使用最简单的方法,仅在性能未达到目标时才引入此类优化。
猜你喜欢
  • 2020-07-29
  • 2013-01-26
  • 2015-06-15
  • 2010-11-11
  • 1970-01-01
  • 2012-03-13
  • 2010-09-29
相关资源
最近更新 更多