2012-03-02 17 views
4
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泛型类型T是如何约束在这个Don Syme的代码上的?

用于:

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 

回答

5

为什么有与x用途做的原因。值xy用作相同回调的参数:f xf y。在此表达式的类型的y已知是T因此x也必须与T所以F#选择T

+0

魔兼容的类型。可能对我来说太过分了。这里是一个我会写下类型的例子。谢谢你的解释 – nicolas 2012-03-02 17:17:07

相关问题