1 // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
13 Defines the `Ord` and `Eq` comparison traits.
15 This module defines both `Ord` and `Eq` traits which are used by the compiler
16 to implement comparison operators.
17 Rust programs may implement `Ord` to overload the `<`, `<=`, `>`, and `>=` operators,
18 and may implement `Eq` to overload the `==` and `!=` operators.
20 For example, to define a type with a customized definition for the Eq operators,
21 you could do the following:
29 // Our implementation of `Eq` to support `==` and `!=`.
30 impl Eq for SketchyNum {
31 // Our custom eq allows numbers which are near eachother to be equal! :D
32 fn eq(&self, other: &SketchyNum) -> bool {
33 (self.num - other.num).abs() < 5
37 // Now these binary operators will work when applied!
38 assert!(SketchyNum {num: 37} == SketchyNum {num: 34});
39 assert!(SketchyNum {num: 25} != SketchyNum {num: 57});
45 * Trait for values that can be compared for equality and inequality.
47 * This trait allows partial equality, where types can be unordered instead of strictly equal or
48 * unequal. For example, with the built-in floating-point types `a == b` and `a != b` will both
49 * evaluate to false if either `a` or `b` is NaN (cf. IEEE 754-2008 section 5.11).
51 * Eq only requires the `eq` method to be implemented; `ne` is its negation by default.
53 * Eventually, this will be implemented by default for types that implement `TotalEq`.
57 /// This method tests for `self` and `other` values to be equal, and is used by `==`.
58 fn eq(&self, other: &Self) -> bool;
60 /// This method tests for `!=`.
62 fn ne(&self, other: &Self) -> bool { !self.eq(other) }
66 * Trait for equality comparisons which are [equivalence relations](
67 * https://en.wikipedia.org/wiki/Equivalence_relation).
69 * This means, that in addition to `a == b` and `a != b` being strict inverses,
70 * the equality must be (for all `a`, `b` and `c`):
72 * - reflexive: `a == a`;
73 * - symmetric: `a == b` implies `b == a`; and
74 * - transitive: `a == b` and `b == c` implies `a == c`.
77 pub trait TotalEq: Eq {
78 // FIXME #13101: this method is used solely by #[deriving] to
79 // assert that every component of a type implements #[deriving]
80 // itself, the current deriving infrastructure means doing this
81 // assertion without using a method on this trait is nearly
84 // This should never be implemented by hand.
87 fn assert_receiver_is_total_eq(&self) {}
90 /// A macro which defines an implementation of TotalEq for a given type.
91 macro_rules! totaleq_impl(
93 impl TotalEq for $t {}
114 /// An ordering is, e.g, a result of a comparison between two values.
115 #[deriving(Clone, Eq, Show)]
117 /// An ordering where a compared value is less [than another].
119 /// An ordering where a compared value is equal [to another].
121 /// An ordering where a compared value is greater [than another].
126 * Trait for types that form a [total order](
127 * https://en.wikipedia.org/wiki/Total_order).
129 * An order is a total order if it is (for all `a`, `b` and `c`):
131 * - total and antisymmetric: exactly one of `a < b`, `a == b` or `a > b`
133 * - transitive, `a < b` and `b < c` implies `a < c`. The same must hold for
136 pub trait TotalOrd: TotalEq + Ord {
137 /// This method returns an ordering between `self` and `other` values.
139 /// By convention, `self.cmp(&other)` returns the ordering matching
140 /// the expression `self <operator> other` if true. For example:
143 /// assert_eq!( 5u.cmp(&10), Less); // because 5 < 10
144 /// assert_eq!(10u.cmp(&5), Greater); // because 10 > 5
145 /// assert_eq!( 5u.cmp(&5), Equal); // because 5 == 5
147 fn cmp(&self, other: &Self) -> Ordering;
150 impl TotalEq for Ordering {}
151 impl TotalOrd for Ordering {
153 fn cmp(&self, other: &Ordering) -> Ordering {
154 (*self as int).cmp(&(*other as int))
158 impl Ord for Ordering {
160 fn lt(&self, other: &Ordering) -> bool { (*self as int) < (*other as int) }
163 /// A macro which defines an implementation of TotalOrd for a given type.
164 macro_rules! totalord_impl(
166 impl TotalOrd for $t {
168 fn cmp(&self, other: &$t) -> Ordering {
169 if *self < *other { Less }
170 else if *self > *other { Greater }
193 * Combine orderings, lexically.
195 * For example for a type `(int, int)`, two comparisons could be done.
196 * If the first ordering is different, the first ordering is all that must be returned.
197 * If the first ordering is equal, then second ordering is returned.
200 pub fn lexical_ordering(o1: Ordering, o2: Ordering) -> Ordering {
208 * Trait for values that can be compared for a sort-order.
210 * Ord only requires implementation of the `lt` method,
211 * with the others generated from default implementations.
213 * However it remains possible to implement the others separately,
214 * for compatibility with floating-point NaN semantics
215 * (cf. IEEE 754-2008 section 5.11).
219 /// This method tests less than (for `self` and `other`) and is used by the `<` operator.
220 fn lt(&self, other: &Self) -> bool;
222 /// This method tests less than or equal to (`<=`).
224 fn le(&self, other: &Self) -> bool { !other.lt(self) }
226 /// This method tests greater than (`>`).
228 fn gt(&self, other: &Self) -> bool { other.lt(self) }
230 /// This method tests greater than or equal to (`>=`).
232 fn ge(&self, other: &Self) -> bool { !self.lt(other) }
235 /// The equivalence relation. Two values may be equivalent even if they are
236 /// of different types. The most common use case for this relation is
237 /// container types; e.g. it is often desirable to be able to use `&str`
238 /// values to look up entries in a container with `~str` keys.
240 /// Implement this function to decide equivalent values.
241 fn equiv(&self, other: &T) -> bool;
244 /// Compare and return the minimum of two values.
246 pub fn min<T: TotalOrd>(v1: T, v2: T) -> T {
247 if v1 < v2 { v1 } else { v2 }
250 /// Compare and return the maximum of two values.
252 pub fn max<T: TotalOrd>(v1: T, v2: T) -> T {
253 if v1 > v2 { v1 } else { v2 }
258 use super::lexical_ordering;
261 fn test_int_totalord() {
262 assert_eq!(5u.cmp(&10), Less);
263 assert_eq!(10u.cmp(&5), Greater);
264 assert_eq!(5u.cmp(&5), Equal);
265 assert_eq!((-5u).cmp(&12), Less);
266 assert_eq!(12u.cmp(-5), Greater);
270 fn test_ordering_order() {
271 assert!(Less < Equal);
272 assert_eq!(Greater.cmp(&Less), Greater);
276 fn test_lexical_ordering() {
277 fn t(o1: Ordering, o2: Ordering, e: Ordering) {
278 assert_eq!(lexical_ordering(o1, o2), e);
281 let xs = [Less, Equal, Greater];
282 for &o in xs.iter() {
285 t(Greater, o, Greater);
290 fn test_user_defined_eq() {
296 // Our implementation of `Eq` to support `==` and `!=`.
297 impl Eq for SketchyNum {
298 // Our custom eq allows numbers which are near eachother to be equal! :D
299 fn eq(&self, other: &SketchyNum) -> bool {
300 (self.num - other.num).abs() < 5
304 // Now these binary operators will work when applied!
305 assert!(SketchyNum {num: 37} == SketchyNum {num: 34});
306 assert!(SketchyNum {num: 25} != SketchyNum {num: 57});