std/core/compare
std/core/src/compare.trb
Equality, order and hashing: Equals, Ordering, Compare and Hash, generated structurally for every type
unless it implements one of them by hand, and combineHashes, what a hand-written hash folds its parts through.
trait Equals
trait Equals
== and !=. Generated by comparing every field, so implement it by hand only where content equality means
something else (a Map that should ignore insertion order, for instance).
Examples
print(1 == 1)
print("a" != "b")
type Ordering
type Ordering
What Compare.compare answers: which of the two values comes first, or that neither does.
trait Compare
trait Compare with Equals
<, <=, >, >=. Requires Equals, so a type that implements Compare gets both from a single compare.
Examples
print(1 < 2)
print 7.clamp(0, 5)
Pitfalls
compareandequalshave to agree:compare(other) == .Equalexactly whereequals(other)istrue. Nothing checks this, so a hand-written pair that disagrees breaks sorting and lookups silently instead of failing loudly.
Related
Ordering- whatcompareanswers.
fn compare
fn compare(other: Self): Ordering
Which of the two values comes first.
fn lessThan
fn lessThan(other: Self): Bool
Whether this value comes before other.
fn greaterThan
fn greaterThan(other: Self): Bool
Whether this value comes after other.
fn min
fn min(other: Self): Self
The smaller of the two values.
fn max
fn max(other: Self): Self
The larger of the two values.
fn clamp
fn clamp(low: Self, high: Self): Self
The value, pulled into [low, high] when it lies outside of it.
trait Hash
trait Hash with Equals
Generated structurally for every type. Values that are equal must have equal hashes, which is why Hash
requires Equals and why a hand-written hash has to fold in exactly the fields a hand-written equals compares.
Related
combineHashes- what a hand-writtenhashfolds its fields through.
fn hash
fn hash(): Int
The integer a hashed Set or Map places the value by.
fn combineHashes
native fn combineHashes(seed: Int, value: Int): Int
Folds one more value into a running hash: wrapping, order-dependent, and deterministic across runs and platforms.
What List folds its items through, in order (see std/collections). A Set or a Map has to
combine its entries regardless of their order instead - bitwiseExclusiveOr (see Bits in std/number),
which cannot overflow, does that.