Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type extension errors for Dictionary<'K, 'V>

The following type extension

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

gives the error:

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

But when I add the constraint it gives the error:

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

This is especially mysterious because the following type extension doesn't have the constraint and works.

type Dictionary<'K, 'V> with
  member this.TryGet(key) =
    match this.TryGetValue(key) with
    | true, v -> Some v
    | _ -> None

Now I'm having weird thoughts: is the constraint required only when certain members are accessed?

like image 434
Daniel Avatar asked Aug 15 '11 14:08

Daniel


1 Answers

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

EDIT:

As per 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>
like image 72
desco Avatar answered Oct 20 '22 06:10

desco