Skip to content

Instantly share code, notes, and snippets.

@OnurGumus
Last active January 2, 2023 15:11
Show Gist options
  • Save OnurGumus/bcb17d0f1b19fc66ed77d47b3e776041 to your computer and use it in GitHub Desktop.
Save OnurGumus/bcb17d0f1b19fc66ed77d47b3e776041 to your computer and use it in GitHub Desktop.
F# boxing equality
open System.Collections.Generic
[<Struct; CustomComparison; CustomEquality>]
type MyVal =
val X : int
new(x) = { X = x }
override this.Equals other =
match other with
| :? MyVal as y -> this.Equals y
| _ -> false
override this.GetHashCode() = this.X
member this.CompareTo (other:MyVal) = this.X.CompareTo(other.X)
member this.Equals (other:MyVal) = other.X = this.X
with
interface System.IComparable<MyVal> with
member this.CompareTo other = failwith "never comes to here"
interface System.IEquatable<MyVal> with
member this.Equals other = other.X = this.X
let inline contains (e:'t) list1 =
let comp = EqualityComparer<'t>.Default;
let rec contains e xs1 =
match xs1 with
| [] -> false
| h1::t1 -> comp.Equals(h1,e)|| contains e t1
contains e list1
let count = 5000
let s = [for i in 0 .. count do
yield MyVal(i)]
System.GC.Collect()
#time
for i in 0 .. count do
contains (MyVal(4999)) s |> ignore
#time
printf "done"
// Real: 00:00:00.135, CPU: 00:00:00.135, GC gen0: 0, gen1: 0, gen2: 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment