5.4 Equality
The == map configuration can be used with forms like the Map.by constructor or Map.by annotation constructor to specify the default equality and hashing functions for map keys. The Map.by(==) annotation, for example, matches only maps that use the default equality and hashing functions.
> "apple" == "apple"
#true
> [1, 2, 3] == 1
#false
> [1, "apple", {"alice": 97}] == [1, "apple", {"alice": 97}]
#true
> 1 == 1.0
#false
The === map configuration can be used with forms like the Map.by constructor or Map.by annotation constructor to specify key equality with === and a corresponding hashing function.
#true
#false
operator | |
| |
operator | |
These comparisons are specialized like + for arguments with Flonum static information.
> 1 .= 1
#true
> 1 .= 2
#false
> 1.0 .= 1
#true
> 1 .!= 2
#true
> 1 .!= 1.0
#false
> "apple" != "apple"
#false
Mutable and immutable strings, byte vectors, and arrays are considered the same if they have the same elements, even if one is mutable and the other is immutable. However, a mutable map or set is never considered equivalent to an immutable map or set, even if they have the same content.
The is_now map configuration can be used with forms like the Map.by constructor or Map.by annotation constructor to specify key equality with is_now and a corresponding hashing function. Beware, however, that mutating a key after it is mapped will tend to make the map entry inaccessible.
> #"apple" is_now Bytes.copy(#"apple")
#true
> #"apple" == Bytes.copy(#"apple")
#false
operator | ||
| ||
map configuration | ||
expression | |
An interface that a class can implement (publicly or privately) to customize the way its objects are compared and hashed. 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.