通用类型'T如何限制在这个Don Syme的代码上?

时间:2012-03-02 16:43:20

标签: generics f# constraints

let compareOn f x (yobj: obj) =
     match yobj with
     | :? 'T as y -> compare (f x) (f y)
     | _ -> invalidArg "yobj" "cannot compare values of different types"

我不知道上面的'T 与x的类型有什么关系。 为什么x的类型不是'a

用于:

type stamp = int

[<CustomEquality; CustomComparison>]
type MyUnionType =
    | MyUnionType of stamp * (int -> int) 

    static member Stamp (MyUnionType (s,_)) = s

    override x.Equals y = equalsOn MyUnionType.Stamp x y
    override x.GetHashCode() = hashOn MyUnionType.Stamp x
    interface System.IComparable with
      member x.CompareTo y = compareOn MyUnionType.Stamp x y

1 个答案:

答案 0 :(得分:5)

之所以与x的使用有关。值xy用作同一回调的参数:f xf y。此表达式中y的类型已知为T,因此x也必须属于与T兼容的类型,因此F#选择T

相关问题