Example implementation of Array's contains that uses tri-state "bikeShedNameHere" method as an optimisation.
func contains(_ element: Element) -> Bool {
var notEqualCount = 0
for v in self {
if let equal = element.bikeShedNameHere(v) { // O(1)
if equal { // identical, thus equal
// quick path -> yes
return true
} else { // quick not equal
notEqualCount += 1
}
}
}
if notEqualCount == count {
// quick path -> no
return false
}
// slow path
for v in self {
if element == v {
return true
}
}
return false
}
Re the name: "distinguishable" or "identical", or similar. Looks they are not great if we want to return a tri-state value including "definitely not equal".
protocol BikeShedNameHere {
func bikeShedNameHere(_ other: Self) -> Bool? // or a tri-state enum
}