有人可以解释为什么F#类型推理在类方法和函数之间似乎有不同的工作方式(或者我不理解的其他方面?)。
想象一下以下(简化):
type Node<'T> = Node2 of 'T * 'T
type Digit<'T> = One of 'T | Two of 'T * 'T
type Tree<'T> =
| Empty
| Single of 'T
| Deep of prefix : Digit<'T> * deeper : Tree<Node<'T>>
with
static member Add (value : 'T) (tree : Tree<'T>) : Tree<'T> =
match tree with
| Empty -> Single value
| Single a -> Deep (One value, Empty)
| Deep (One a, deeper) -> Deep (Two (value, a), deeper)
| Deep (Two (b, a), deeper) -> Deep (One value, deeper |> Tree.Add (Node2 (b, a)))
let rec add (value : 'T) (tree : Tree<'T>) : Tree<'T> =
match tree with
| Empty -> Single value
| Single a -> Deep (One value, Empty)
| Deep (One a, deeper) -> Deep (Two (value, a), deeper)
| Deep (Two (b, a), deeper) -> Deep (One value, deeper |> add (Node2 (b, a)))
请注意,静态方法Add
和函数add
具有相同的实现,并且都以递归方式调用自身。
然而,前者编译得很好但后者报告错误:
Type mismatch. Expecting a
Tree<Node<'T>> -> Tree<Node<'T>>
but given a
Tree<'T> -> Tree<'T>
The resulting type would be infinite when unifying ''T' and 'Node<'T>'
答案 0 :(得分:3)
在自由浮动函数add
中,泛型类型参数属于函数本身(add<'T>
)。
但是,在静态成员函数中,type参数实际上属于类(Tree<'T>
)。
为什么这很重要?因为当您引用函数本身时,除非另行指定,否则编译器会假定type参数未更改。它不会猜到另一个,因为这可能会隐藏一大类不匹配错误。
但是,它并没有对函数所属的类型做出相同的假设。
如果检查参数,则假定对add
的调用是对add<'T>
的调用,这会导致无限泛型递归并且不会编译。
但是,对Tree.Add
的调用被推断为对Tree<Node<'T>>.Add
,不到Tree<'T>.Add
的调用。它完全是一个不同的函数调用。
如果明确注释类型:
static member Add (value : 'T) (tree : Tree<'T>) : Tree<'T> =
// ...
| Deep (Two (b, a), deeper) -> Deep (One value, deeper |> Tree<'T>.Add (Node2 (b, a)))
您将获得与自由函数完全相同的类型不匹配/无限类型错误。
同样,如果您将其设为实例成员并引用相同的实例,则会收到错误:
member this.Add (value : 'T) (tree : Tree<'T>) : Tree<'T> =
// ...
| Deep (Two (b, a), deeper) -> Deep (One value, deeper |> this.Add (Node2 (b, a)))
反之亦然,你可以通过注释类型参数来编译自由函数,这样编译器就不会假设它是相同的符号,所以必须引用相同的值&#34; :
let rec add<'T> (value : 'T) (tree : Tree<'T>) : Tree<'T> =
// ...
| Deep (Two (b, a), deeper) -> Deep (One value, deeper |> add (Node2 (b, a)))