Dave
Dave

Reputation: 2386

Overloading Equality and Comparison Operators with non Bool Return types

Is there a specific reason why overriding the equality and comparison operators to produce a type other than bool is so difficult.

I have a workaround below, but why wouldn't the language make this easier to do?

What I am working with here is an external library which has these operators overloaded already, I simply want them to work the same way in F#. It just doesn't seem right that I have to do this in order to accomplish that.

type ATArrayLT = ATArrayLT with
    static member        (?<-) (x:ATArray, ATArrayLT, y:int    ) = ATArray.op_LessThan(x, float32 y)
    static member        (?<-) (y:int    , ATArrayLT, x:ATArray) = ATArray.op_LessThan(x, float32 y)        
    static member        (?<-) (x:ATArray, ATArrayLT, y:float32) = ATArray.op_LessThan(x, y)
    static member        (?<-) (y:float32, ATArrayLT, x:ATArray) = ATArray.op_LessThan(x, y)
    static member        (?<-) (x:ATArray, ATArrayLT, y:ATArray) = ATArray.op_LessThan(x, y)
    static member inline (?<-) (x        , ATArrayLT, y        ) = x < y

let inline (<) x y = x ? (ATArrayLT) <- y

Upvotes: 2

Views: 494

Answers (1)

Daniel
Daniel

Reputation: 47904

The comparison and equality operators (<, >, =) have well-defined behavior (spec §8.15.6). Specifically, comparison depends on an IComparable implementation and equality depends on Equals.

There is only a passing resemblance to the operators of the same name in C#. You can still provide the C# variants, complete with non-traditional behavior, to be used from other .NET languages

type T() =
  static member op_LessThan (a: T, b: T) = new obj()

but they have no effect on F#'s equality and comparison operators.

Upvotes: 1

Related Questions