gpt4 book ai didi

dictionary - 字典 <'K, ' V> 的类型扩展错误

转载 作者:行者123 更新时间:2023-12-04 12:12:40 26 4
gpt4 key购买 nike

以下类型扩展

module Dict =

open System.Collections.Generic

type Dictionary<'K, 'V> with
member this.Difference(that:Dictionary<'K, 'T>) =
let dict = Dictionary()
for KeyValue(k, v) in this do
if not (that.ContainsKey(k)) then
dict.Add(k, v)
dict

给出错误:

The signature and implementation are not compatible because the declaration of the type parameter 'TKey' requires a constraint of the form 'TKey : equality



但是当我添加约束时,它给出了错误:

The declared type parameters for this type extension do not match the declared type parameters on the original type 'Dictionary<,>'



这特别神秘,因为以下类型扩展没有约束并且有效。
type Dictionary<'K, 'V> with
member this.TryGet(key) =
match this.TryGetValue(key) with
| true, v -> Some v
| _ -> None

现在我有奇怪的想法:是否只有在访问某些成员时才需要约束?

最佳答案

module Dict =

open System.Collections.Generic

type Dictionary<'K, 'V> with
member this.Difference(that:Dictionary<'K, 'T>) =
let dict = Dictionary(this.Comparer)
for KeyValue(k, v) in this do
if not (that.ContainsKey(k)) then
dict.Add(k, v)
dict

编辑 :

根据 F# spec (14.11 Additional Constraints on CLI Methods)

Some specific CLI methods and types are treated specially by F#, because they are common in F# programming and cause extremely difficult-to-find bugs. For each use of the following constructs, the F# compiler imposes additional ad hoc constraints:

  • x.Equals(yobj) requires type ty : equality for the static type of x
  • x.GetHashCode() requires type ty : equality for the static type of x
  • new Dictionary<A,B>() requires A : equality, for any overload that does not take an IEqualityComparer<T>

关于dictionary - 字典 <'K, ' V> 的类型扩展错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7065950/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com