9.1 Equatables
Any value is equatable. Implementing the Equatable interface customizes the way that instances of a class are compared for == and hashed for maps and sets that use ==.
An interface that a class can implement (publicly or privately) to customize the way its objects are compared for == and hashed for maps and sets that use ==. The interface has two methods:
equals(other, recur) —
takes another object that is an instance of the same class (or a subclass), and returns a non-#false value if the objects are equal, #false otherwise. Use the given recur function to compare components of the two objects, instead of using == on the components. hash_code(recur) —
returns a hash code for the object, which is an exact integer. Use recur to compute hash code for components of the object, and use the functions Equatable.hash_code_combine and Equatable.hash_code_combine_unordered to combine component hash codes.
A class gets a default equality implementation that recurs to compare fields only if the class has no mutable fields, and that matches === when the class has mutable fields. Normally, Equatable should be implemented privately, so that the methods do not have to check what class other instantiates or whether recur is a function.
class Posn(x, y):
method dist():
cache := v
v)
// since `cache` is mutable, the default equality
// comparison would only make `===` objects equal
Equatable.hash_code_combine(recur(x), recur(y))
> Posn(3, 4) == Posn(3, 4)
#true
function | ||
| ||
| ||
function | ||
|
See Equatable for an example.