Skip to content

Instantly share code, notes, and snippets.

@bent-rasmussen
Last active February 19, 2022 17:34
Show Gist options
  • Save bent-rasmussen/17a6f52810734276b56c10328af35a89 to your computer and use it in GitHub Desktop.
Save bent-rasmussen/17a6f52810734276b56c10328af35a89 to your computer and use it in GitHub Desktop.
How I learned to love the struct and stop worrying (part I)...
/// Equatable operators - avoid boxing operands when comparing structs.
/// Source: https://github.com/dotnet/fsharp/issues/526#issuecomment-119755563
module EquatableOperators =
let inline eq<'a when 'a :> System.IEquatable<'a>> (x:'a) (y:'a) = x.Equals y
let inline (==) x y = eq x y
let inline (!=) x y = not (eq x y)
/// We get a fair warning that it's odd that we impl. custom equality
/// when we deny the equality operator.
[<Struct; NoEquality; NoComparison>]
type BoxAversePoint =
{ X: int
Y: int }
interface IEquatable<BoxAversePoint> with
member x.Equals y =
x.X = y.X &&
x.Y = y.Y
let a = { X = 1; Y = 2 }
let b = a
let c = { X = -1; Y = -2 }
// Do not (and now cannot - due to NoEquality)
//do a = b |> ignore // boxes operands, structs allocate memory
//do a = c |> ignore // boxes operands, structs allocate memory
open EquatableOperators
// Do
do a == b |> ignore // no boxing
do a == c |> ignore // no boxing
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment