Reference

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")

fn equals

fn equals(other: Self): Bool

Whether the two values are equal. This is ==.

fn notEquals

fn notEquals(other: Self): Bool

Whether the two values differ. This is !=.

type Ordering

type Ordering

What Compare.compare answers: which of the two values comes first, or that neither does.

case Less

case Less

The first value comes before the second.

case Equal

case Equal

The two values are equal.

case Greater

case Greater

The first value comes after the second.

fn reversed

fn reversed(): Ordering

Flips the direction, so sorting by the reverse of a key is comparing with this instead.

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

  • compare and equals have to agree: compare(other) == .Equal exactly where equals(other) is true. Nothing checks this, so a hand-written pair that disagrees breaks sorting and lookups silently instead of failing loudly.

Related

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-written hash folds 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.