In answering this question, I discovered the following behaviour of compare
on discriminated unions.
type T = A | B | C | D
compare A B (* val it : int = -1 *)
compare A C (* val it : int = -2 *)
compare A D (* val it : int = -3 *)
I was surprised by this.
Can I rely on compare
measuring the "distance" between constructors like this?
The spec says (p. 154) about the generated compareTo
:
If T is a union type, invoke Microsoft.FSharp.Core.Operators.compare first on the index of the union cases for the two values, and then on each corresponding field pair of x and y for the data carried by the union case. Return the first non-zero result.
From that, I'd expect compare
on type T
to always give one of -1,0,1
since that's how compare
behaves on numeric types. (Right?)
CompareTo(other)
as (this - other), for example((short)2).CompareTo((short)5)
returns -3. – Octanglecompare
function in F#. For example2s.CompareTo(5s)
returns-3
as you say, butcompare 2s 5s
returns just-1
. – Robena