docs

你正在阅读 v0.1.2 的文档。Nabi 0.1.2 已不再提供支持。 最新版本:v0.1.3 →

本页尚未翻译,以下为英文原文。

#2.5. Comparison traits

本页内容

This chapter covers the trait family that defines comparison between values. Not only the ==, !=, <, >, <=, >= operators but also hashing, sorting and pattern matching dispatch through the traits of this chapter.

The traits live in two modules. PartialEq and PartialOrd carry the comparison operators, so they are defined in core::ops with the other operator traits (2.3). Eq, Ord, Hash and Ordering are defined in core::cmp. PartialEq, PartialOrd, Eq, Ord, Hash and Ordering are in the prelude (0.2.3), so user code names them without a use. The hashers a Hash impl writes to are in core::hash (2.5.11).

Nabi splits comparison into a 4-trait hierarchy (PartialEq / Eq / PartialOrd / Ord) plus a separate Hash trait. The split satisfies two practical requirements at once: NaN handling for IEEE 754 floating-point, and guaranteed hash consistency.

#2.5.1. The 4-trait hierarchy - why partial is needed

The hierarchy can be described from two viewpoints at once.

Set viewpoint: A ⊃ B means "the set of types satisfying A contains the set of types satisfying B". A is more general; B is more specific.

PartialEq  ⊃  Eq           // set of PartialEq types ⊇ set of Eq types
PartialOrd ⊃  Ord          //  (every Eq is PartialEq, but not vice versa)
PartialEq  ⊃  PartialOrd

Implication viewpoint (supertrait): B ⇒ A means "implementing B automatically requires A"; in Nabi code it is written trait B: A. A is then a supertrait of B.

nabi
trait Eq: PartialEq { ... }                    // PartialEq is a supertrait of Eq
trait PartialOrd: PartialEq { ... }            // PartialEq is a supertrait of PartialOrd
trait Ord: PartialOrd + Eq { ... }             // PartialOrd and Eq are supertraits of Ord

The two viewpoints express exactly the same fact from different angles. If B ⇒ A, every type that is B is also A, so A ⊃ B follows. In the set viewpoint, the supertrait is "the larger side".

The Hash trait sits on a line separate from the hierarchy above.

Eq ⊃ Hash         // only some Eq types are Hash; Hash promises consistency with Eq

Partial is split out because of NaN in IEEE 754 floating point.

nabi
let a: f64 = 0.0 / 0.0;       // NaN
let b: f64 = 0.0 / 0.0;       // NaN
a == b;                       //→ false (NaN != NaN by IEEE 754)
a < b;                        //→ false
a > b;                        //→ false
a <= b;                       //→ false

NaN is not equal even to itself. This violates reflexivity: a == a is not guaranteed. Trait implementations therefore split by type: f32 and f64 implement only PartialEq, PartialOrd, while i32, bool, str and the like implement up to Eq, Ord and satisfy a total order.

This split keeps Hash's consistency promise and the total ordering guarantee safe in Hash, Dict / Set and sort algorithms.

#2.5.2. PartialEq - partial equality (==, !=)

Partial equality is defined as follows.

nabi
#[lang("eq_trait")]
trait PartialEq<Rhs = Self> {
    #[infix("==")]
    fn eq(self, rhs: Rhs) -> bool;

    #[infix("!=")]
    fn ne(self, rhs: Rhs) -> bool {
        !self.eq(rhs)                // default impl
    }
}

The Unicode tokens ≡ and ≠ have no infix bindings of their own. The lexer reads them as == and != (refs-lang 1.10.3), so they dispatch to eq and ne.

The promises of PartialEq are symmetry (a == b and b == a are equivalent) and transitivity (if a == b and b == c hold, a == c holds). Reflexivity (a == a) is not guaranteed, because of IEEE 754 NaN.

#Default ne

ne is implemented by default as !self.eq(rhs). A user may implement it separately, e.g. for performance.

#Examples

nabi
let r1 = 5i32 == 5i32;     //→ true
let r2 = "hi" != "hello";  //→ true

let nan: f64 = f64::NAN;
let r3 = nan == nan;       //→ false  (PartialEq is partial)

#2.5.3. Eq - total equality

Total equality is defined as a marker trait.

nabi
trait Eq: PartialEq<Self> {
    // marker trait: no additional methods
}

Eq is a marker trait: it adds no methods, only the reflexivity promise.

The promise Eq adds is reflexivity: a == a is always true. Dict / Set keys and sort algorithms work correctly only with this promise.

The impl policy is as follows. All integer / boolean / character / string types (i32, i64, u8..u64, bool, char, c_char, str, etc.) implement Eq. Floating-point types and sum types containing them (f32, f64, f64 | none, etc.) do not implement Eq. #[derive(Eq)] on a user struct or enum is possible only when every field is Eq.

nabi
let n: i32 = 42;
n == n;       //→ true (guaranteed by Eq)

#2.5.4. PartialOrd - partial order (<, >, <=, >=)

The partial order trait defines the comparison operators.

As with ≡ and ≠, the lexer reads ≤ and ≥ as <= and >=.

The promises of this trait: antisymmetry (if a < b then !(b < a)) and transitivity (for defined comparisons, if a < b and b < c then a < c). Trichotomy holds only partially: the order between two values is not always defined, and incomparable values such as NaN exist.

partial_cmp is a provided method (with a default implementation) and returns Ordering | none. It is none when the values are incomparable (NaN, etc.).

#The Ordering type

The result of a 3-way comparison is represented by this enum.

nabi
enum Ordering {
    Less,
    Equal,
    Greater,
}

Ord::cmp returns Ordering directly. Ordering implements Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash and Debug (Less / Equal / Greater; Less < Equal < Greater), and has these inherent methods.

nabi
impl Ordering {
    const fn is_lt(self) -> bool;        // self is Less
    const fn is_eq(self) -> bool;        // self is Equal
    const fn is_gt(self) -> bool;        // self is Greater
    const fn reverse(self) -> Ordering;  // swaps Less and Greater; Equal stays
    const fn then(self, other: Ordering) -> Ordering;      // self, or other when self is Equal
    fn then_with(self, f: fn() -> Ordering) -> Ordering;   // self, or f() when self is Equal
}
nabi
let o = 3.cmp(7);     //→ Less
o.is_lt();            //→ true
o.reverse();          //→ Greater
xs.sort_by(|a: (i64, i64), b: (i64, i64)| a.0.cmp(b.0).then(a.1.cmp(b.1)));   // ties by .1

#Comparison chains

As defined by refs-lang 3.2.5, comparisons of one direction chain, each operand evaluated once:

nabi
lo <= x < hi;     // lo <= x && x < hi
a < b > c;        // compile error: two directions; write a < b && b > c

#2.5.5. Ord - total order

The total order trait is defined as follows.

The promise Ord adds is totality: the order between any two values is defined as one of Less, Equal, Greater. partial_cmp therefore never returns none; it always returns an Ordering value.

Sort algorithms work correctly only with this guarantee.

Impl policy: i32, i64, u*, bool, char, c_char, str implement Ord. f32 and f64 do not, because NaN makes some values incomparable.

#min / max / clamp

Three default methods are provided, usable without the impl implementing them. On a tie min returns self and max returns rhs, so of equal values min keeps the first and max the last, as Iterator::min / max do (2.7). clamp panics when low > high, like f64::clamp.

nabi
let r = 3i32.min(7i32);              //→ 3
let m = 5.max(10);                   //→ 10
let c = 100.clamp(0, 50);            //→ 50
let o = 1.0f64.cmp(2.0);             // ERROR: Ord is not defined for f64
let k = 1.0f64.clamp(0.0, 10.0);     //→ 1.0: the inherent f64::clamp (2.1.4), not Ord's

#2.5.6. Hash - hashing (Eq consistency promise)

A Hash value feeds itself to a Hasher (2.5.11), which turns what it was given into a u64.

nabi
#[lang("hash_trait")]
trait Hash: Eq {
    fn hash<H: Hasher>(self, ref h: H);
}

The core promise is:

a == b ⇒ a and b make the same sequence of writes, so every hasher gives them the same hash

This promise underpins the correctness of every algorithm in Dict<K, V, S> and Set<T, S>.

Since Hash: Eq, a type that does not implement Eq cannot implement Hash either. f64 does not implement Eq, so it cannot implement Hash.

#What an impl writes

An impl writes its parts in a fixed order, each with its own hash or a write_<int> of the Hasher. A variable-length run of values (a list's items) starts with h.write_length_prefix(len). Without it, adjacent runs could shift into each other: [[1, 2], [3]] and [[1], [2, 3]] would make the same writes. write_str is prefix-free by itself and is never preceded by write_length_prefix.

The standard impls write:

TypeWrites
i*, u*write_<type>(self); usize / isize as 8 bytes on every target
boolwrite_u8(0 / 1)
char / c_charwrite_u32 / write_u8
strwrite_str(self)
List<T>write_length_prefix(len), then each item
[T; N]each item (N is part of the type)
tupleseach component in order
sum A | Bwrite_usize(member index), then the member's hash
NonZero / Positivethe inner value
NonNan / Finitethe bits as write_u64, -0.0 as 0.0
Intthe sign, write_length_prefix(limbs), then the 32-bit limbs; the same for every form of one value
Dict<K, V, S> / Set<T, S>each entry hashed alone with a hasher of RandomState::new(), the results summed (wrapping); then write_length_prefix(len) and write_u64(sum)

Dict and Set hash independently of order, as they compare. Every entry uses the process key whatever S is, so two equal dicts hash alike even when their S differ.

#Getting a hash

There is no one-call form: build a hasher, write, finish.

nabi
use core::hash::{BuildHasher, RandomState};

let h = RandomState::new().build_hasher();
"hello".hash(ref h);
let a = h.finish();       // the same for "hello" all through this run

#User-defined

nabi
#[derive(PartialEq, Eq, Hash)]
struct UserId { id: u64; }

// automatic derive: possible because every field (id: u64) is Eq+Hash

A hand-written impl writes exactly what equality looks at:

nabi
use core::hash::Hasher;

struct Tag { name: str; }

impl PartialEq for Tag {
    fn eq(self, rhs: Tag) -> bool { self.name.to_lowercase() == rhs.name.to_lowercase() }
    fn ne(self, rhs: Tag) -> bool { !self.eq(rhs) }
}
impl Eq for Tag {}

impl Hash for Tag {
    fn hash<H: Hasher>(self, ref h: H) {
        h.write_str(self.name.to_lowercase());   // equal tags write the same
    }
}

#Collisions

Two different values of the same type may hash alike, even when a != b. This is not a bug: collisions are unavoidable in a 64-bit hash space. Data structures such as Dict handle collisions.

#Stability

The core promise is the only one. A hash value may differ between runs of the same program, between machines and between Nabi versions, and so may the writes an impl makes. A program must not store a hash or send it to another process; a hash that must stay the same comes from SipHasher13 / SipHasher24 fed bytes and integers directly (2.5.11), never from x.hash(ref h). Dict and Set hash with RandomState by default, whose key is drawn at random once per process, so where a key lands in the table differs from run to run; what they iterate and print does not, since that is insertion order (2.9.3).

#2.5.7. Implementation matrix

Trait implementations per type are summarized below.

TypePartialEqEqPartialOrdOrdHashBehavior
i*, u*✓✓✓✓✓nabi.eq.OP, nabi.lt.OP, ...
f32, f64✓✗✓✗✗nabi.eq.f64, nabi.lt.f64
bool✓✓✓✓✓nabi.eq.bool (< a plain body)
char, c_char✓✓✓✓✓nabi.eq.char, ...
str✓✓✓✓✓lexicographic
Tuple<...>✓ (when every part is PartialEq)✓✓✓✓lexicographic, 1-12 elements
[T; N]✓ (T:PartialEq)✓✓✓✓lexicographic
List<T>✓ (when T:PartialEq)✓✓✓✓lexicographic
Dict<K,V,S>✓ (K:Hash, V:PartialEq)✓ (V:Eq)✗✗✓ (V:Hash)order-independent comparison / hash
Set<T,S>✓ (T:Hash)✓✗✗✓order-independent comparison / hash
Range<T>✓ (T:PartialEq)✓ (T:Eq)✗✗✓ (T:Hash)start/end comparison
Sum A | B✓ (when every member implements it)✓T | none onlyT | none only✓none first → payload

Dict and Set are unordered containers, so they have no PartialOrd / Ord. Every Dict and Set impl requires the keys (set elements) to be Hash. Set<T, S> is PartialEq, Eq and Hash for any T: Hash. Dict<K, V, S> with K: Hash is PartialEq when V: PartialEq, Eq when V: Eq and Hash when V: Hash. That holds for every S: BuildHasher: equality ignores S. Both compare and hash independently of iteration order (2.9).

List compares lexicographically: elements are compared from the front, the first differing element decides the order, and if one is a prefix of the other, the shorter one is smaller.

Only a sum with at most one term besides none is ordered (refs-lang 2.6.4). T | none is PartialOrd / Ord when T is: none is less than any T value (as in Rust and Haskell), and two T values compare by T's order. min / max / clamp follow the same order. A sum with two or more terms besides none (i32 | str) has no PartialOrd / Ord: comparing or sorting its values is a compile error; order them by a key (sort_by_key, sort_by, min_by_key).

#2.5.8. Broadcast comparison traits

Of the 20 broadcast traits of 2.6 broadcast, the 6 comparison traits are defined as follows.

nabi
trait DotEq<Rhs>  { #[infix(".==")] fn dot_eq(...) -> Output; }
trait DotNe<Rhs>  { #[infix(".!=")] fn dot_ne(...) -> Output; }
trait DotLt<Rhs>  { #[infix(".<")] fn dot_lt(...) -> Output; }
trait DotGt<Rhs>  { #[infix(".>")] fn dot_gt(...) -> Output; }
trait DotLe<Rhs>  { #[infix(".<=")] fn dot_le(...) -> Output; }
trait DotGe<Rhs>  { #[infix(".>=")] fn dot_ge(...) -> Output; }

Each trait handles element-wise comparison of containers such as List or Vec3; the result type (Output) is usually List<bool> or [bool; N].

See 2.6 broadcast for the full broadcast semantics.

#2.5.9. #[derive(Eq, Ord, Hash, ...)]

refs-lang 6.2 #[derive] defines the derive mechanism. All five cmp traits can be derived.

nabi
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)]
struct Version { major: u32; minor: u32; patch: u32; }

Derive behavior per trait: PartialEq and Eq are defined as the AND of equality of all fields. PartialOrd and Ord compare lexicographically in field declaration order. Hash writes the fields in declaration order, each with its own hash; an enum first writes its variant index with write_usize, except an enum of one variant. The exact writes are not stable (2.5.6).

The requirement is that every field (recursively) implements the same trait, and Eq / Ord also require their supertraits (PartialEq / PartialOrd, Eq) to be derived or implemented. If even one field does not implement Eq, #[derive(Eq)] is a compile error.

#2.5.10. Pattern matching and cmp

Literal patterns in match arms use PartialEq::eq.

nabi
match x {
    0 => "zero",
    1 => "one",
    _ => "other",
}
// → 0.eq(x) → compare, 1.eq(x) → compare, ...

Range patterns (0..=10 =>) use PartialOrd::le and ge.

See refs-lang 3.11 Patterns for the full pattern semantics.

#2.5.11. core::hash - hashers

The module holds what a Hash impl writes to. It is not in the prelude: user code imports what it names (use core::hash::Hasher; for a hash<H: Hasher> impl, use core::hash::{BuildHasher, RandomState};). Calling a Hasher method on a value (h.write_str(..)) needs no use, as for every standard library trait.

  • RandomState holds a 128-bit key drawn from the operating system's random source the first time a program asks for one. Every RandomState::new() in one process holds the same key, so two dicts with equal keys use the same hasher. It is Copy, Eq, Default, and its Debug shows no key. It is the default S of Dict and Set (2.9.3).
  • DefaultHasher is RandomState's hasher. Its algorithm (SipHash-1-3 today) and so its output are unspecified and may change in any release. Its write_str writes the bytes and then the byte 0xFF, which UTF-8 never holds, instead of a length.
  • A RandomState built at compile time (a const, or a value made during constant evaluation) holds the all-zero key, which the run time never draws. At run time it stands for the process key. A table hashed with it during constant evaluation is rehashed with the process key on its first use at run time, once.
  • BuildHasherDefault<H> builds H::default() for every hash, for a Dict / Set with a hasher of the caller's (Dict<K, V, BuildHasherDefault<Fnv>>). A fixed, unkeyed hasher is faster but lets anyone who chooses the keys make them collide; use one only when keys cannot come from an attacker. Faster hashers come from packages.
  • Debug: DefaultHasher, SipHasher13, SipHasher24 and BuildHasherDefault<H> print their type name and no state (SipHasher13 { .. }), so a key never reaches a log.
  • SipHasher13 / SipHasher24 are SipHash-1-3 and SipHash-2-4 under the caller's key. Their output for the bytes written is the reference SipHash and stays the same across releases and targets: write_<int> writes the integer's little-endian bytes, write_usize 8 of them. Only the bytes and integers a program writes itself are stable; the writes of a Hash impl are not (2.5.6), so a stored hash, such as a sharding key, never comes from x.hash(ref h).
nabi
use core::hash::SipHasher13;

fn shard(user: str, shards: u64) -> u64 {
    let h = SipHasher13::with_keys(0x5eed, 0);
    h.write(user);                // the bytes alone: stable
    h.finish() % shards
}

For cryptographic strength use core::crypto (SHA-2, SHA-3) instead.

Found a mistake? Edit this page on GitHub. Last updated