How is generic type 'T constrained on this Don Syme's code?

189 views Asked by At
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"

I don't see how 'T above relates to the type of x. Why is not the type of x just 'a ?

Used in:

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

There are 1 answers

1
JaredPar On BEST ANSWER

The reason why has to do with the uses of x. The value x and y are used as arguments to the same call back: f x and f y. The type of y in this expression is known to be T hence x must also be of a type compatible with T so F# chooses T