Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# Record Structural Comparison Ordering

If I have an record such as:

type MyDate =
    { Year  : int
      Month : int
      Day   : int }

I know that F#'s structural comparison will ensure that when a list is sorted it will maintain a consistent order.

My question is whether I can rely on it to do the comparison in a specific way, and what that way is?

For example with the MyDate record above: if it compares each field in the order they were declared then I could assume the following: { Year: 2010; Month: 9: Day: 8 } > { Year: 2009; Month: 10; Day: 20 }

I've struggled to find the documentation that describes how the structure equality for Record types work. I can see from the Fsharp.Core tests how tuple comparison works: https://github.com/fsharp/fsharp/blob/cb6cb5c410f537c81cf26825657ef3bb29a7e952/tests/fsharp/core/attributes/test.fsx#L737, but I can't seem to find a similar test for Record types.

like image 526
Tub Avatar asked Sep 20 '19 11:09

Tub


1 Answers

Ah, straight after I posted the question I managed to find the answer:

From the language spec: https://fsharp.org/specs/language-spec/4.1/FSharpSpec-4.1-latest.pdf

8.15.4 Behavior of the Generated CompareTo Implementations

...

• If T is a struct or record type, invoke FSharp.Core.Operators.compare on each corresponding pair of fields of x and y in declaration order, and return the first non-zero result.

So in the above MyDate example, when comparing two instances it will:

  1. compare the Year fields first
  2. then if the years are the same it will compare the Month fields
  3. then if the months are the same it will compare the Day fields
like image 179
Tub Avatar answered Nov 04 '22 07:11

Tub