Equality inference in F# + records with mutable fields
The common equality/comparison members design guideline is to not implement structural equality on mutable reference types, but take a look at F# record types with mutable fields:
type Value = { mutable value: int }
let mutableRecord = { value = 1 }
let xs = Map.ofList [ mutableRecord, "abc"
{ value = 2 }, "def" ]
let abc = Map.find { value=1 } xs
mutableRecord.value <- 3
let abc = Map.find { value=3 } xs // KeyNotFoundException!
The Map
is sorted internally, but mutable
record fields allows me to change ordering while record instance is already inside map and this is very bad.
I think F# should infer [<NoEquality>]
and [<NoComparison>]
modes for F# record types that declares mutable fields, isn't i开发者_如何学Got?
That's not an unreasonable stance.
There might be some clever ways to leverage this feature usefully, though I haven't thought about it deeply enough. This is basically the same thing as when you put a mutable type in a Dictionary
, and you get what you deserve. (Languages can't prevent every misuse, which is why we have design guidelines and programmer judgment to fill in the gaps :) )
Anyway, there's no changing it now.
精彩评论