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.
11 //! Defines the `Ord` and `Eq` comparison traits.
13 //! This module defines both `Ord` and `Eq` traits which are used by the
14 //! compiler to implement comparison operators. Rust programs may implement
15 //!`Ord` to overload the `<`, `<=`, `>`, and `>=` operators, and may implement
16 //! `Eq` to overload the `==` and `!=` operators.
18 //! For example, to define a type with a customized definition for the Eq
19 //! operators, you could do the following:
23 //! struct SketchyNum {
27 //! // Our implementation of `Eq` to support `==` and `!=`.
28 //! impl Eq for SketchyNum {
29 //! // Our custom eq allows numbers which are near eachother to be equal! :D
30 //! fn eq(&self, other: &SketchyNum) -> bool {
31 //! (self.num - other.num).abs() < 5
35 //! // Now these binary operators will work when applied!
36 //! assert!(SketchyNum {num: 37} == SketchyNum {num: 34});
37 //! assert!(SketchyNum {num: 25} != SketchyNum {num: 57});
40 /// Trait for values that can be compared for equality and inequality.
42 /// This trait allows partial equality, where types can be unordered instead of
43 /// strictly equal or unequal. For example, with the built-in floating-point
44 /// types `a == b` and `a != b` will both evaluate to false if either `a` or
45 /// `b` is NaN (cf. IEEE 754-2008 section 5.11).
47 /// Eq only requires the `eq` method to be implemented; `ne` is its negation by
50 /// Eventually, this will be implemented by default for types that implement
54 /// This method tests for `self` and `other` values to be equal, and is used by `==`.
55 fn eq(&self, other: &Self) -> bool;
57 /// This method tests for `!=`.
59 fn ne(&self, other: &Self) -> bool { !self.eq(other) }
62 /// Trait for equality comparisons which are [equivalence relations](
63 /// https://en.wikipedia.org/wiki/Equivalence_relation).
65 /// This means, that in addition to `a == b` and `a != b` being strict
66 /// inverses, the equality must be (for all `a`, `b` and `c`):
68 /// - reflexive: `a == a`;
69 /// - symmetric: `a == b` implies `b == a`; and
70 /// - transitive: `a == b` and `b == c` implies `a == c`.
71 pub trait TotalEq: Eq {
72 // FIXME #13101: this method is used solely by #[deriving] to
73 // assert that every component of a type implements #[deriving]
74 // itself, the current deriving infrastructure means doing this
75 // assertion without using a method on this trait is nearly
78 // This should never be implemented by hand.
81 fn assert_receiver_is_total_eq(&self) {}
84 /// A macro which defines an implementation of TotalEq for a given type.
85 macro_rules! totaleq_impl(
87 impl TotalEq for $t {}
108 /// An ordering is, e.g, a result of a comparison between two values.
109 #[deriving(Clone, Eq, Show)]
111 /// An ordering where a compared value is less [than another].
113 /// An ordering where a compared value is equal [to another].
115 /// An ordering where a compared value is greater [than another].
119 /// Trait for types that form a [total order](
120 /// https://en.wikipedia.org/wiki/Total_order).
122 /// An order is a total order if it is (for all `a`, `b` and `c`):
124 /// - total and antisymmetric: exactly one of `a < b`, `a == b` or `a > b` is
126 /// - transitive, `a < b` and `b < c` implies `a < c`. The same must hold for
127 /// both `==` and `>`.
128 pub trait TotalOrd: TotalEq + Ord {
129 /// This method returns an ordering between `self` and `other` values.
131 /// By convention, `self.cmp(&other)` returns the ordering matching
132 /// the expression `self <operator> other` if true. For example:
135 /// assert_eq!( 5u.cmp(&10), Less); // because 5 < 10
136 /// assert_eq!(10u.cmp(&5), Greater); // because 10 > 5
137 /// assert_eq!( 5u.cmp(&5), Equal); // because 5 == 5
139 fn cmp(&self, other: &Self) -> Ordering;
142 impl TotalEq for Ordering {}
143 impl TotalOrd for Ordering {
145 fn cmp(&self, other: &Ordering) -> Ordering {
146 (*self as int).cmp(&(*other as int))
150 impl Ord for Ordering {
152 fn lt(&self, other: &Ordering) -> bool { (*self as int) < (*other as int) }
155 /// A macro which defines an implementation of TotalOrd for a given type.
156 macro_rules! totalord_impl(
158 impl TotalOrd for $t {
160 fn cmp(&self, other: &$t) -> Ordering {
161 if *self < *other { Less }
162 else if *self > *other { Greater }
184 /// Combine orderings, lexically.
186 /// For example for a type `(int, int)`, two comparisons could be done.
187 /// If the first ordering is different, the first ordering is all that must be returned.
188 /// If the first ordering is equal, then second ordering is returned.
190 pub fn lexical_ordering(o1: Ordering, o2: Ordering) -> Ordering {
197 /// Trait for values that can be compared for a sort-order.
199 /// Ord only requires implementation of the `lt` method,
200 /// with the others generated from default implementations.
202 /// However it remains possible to implement the others separately,
203 /// for compatibility with floating-point NaN semantics
204 /// (cf. IEEE 754-2008 section 5.11).
207 /// This method tests less than (for `self` and `other`) and is used by the `<` operator.
208 fn lt(&self, other: &Self) -> bool;
210 /// This method tests less than or equal to (`<=`).
212 fn le(&self, other: &Self) -> bool { !other.lt(self) }
214 /// This method tests greater than (`>`).
216 fn gt(&self, other: &Self) -> bool { other.lt(self) }
218 /// This method tests greater than or equal to (`>=`).
220 fn ge(&self, other: &Self) -> bool { !self.lt(other) }
223 /// The equivalence relation. Two values may be equivalent even if they are
224 /// of different types. The most common use case for this relation is
225 /// container types; e.g. it is often desirable to be able to use `&str`
226 /// values to look up entries in a container with `~str` keys.
228 /// Implement this function to decide equivalent values.
229 fn equiv(&self, other: &T) -> bool;
232 /// Compare and return the minimum of two values.
234 pub fn min<T: TotalOrd>(v1: T, v2: T) -> T {
235 if v1 < v2 { v1 } else { v2 }
238 /// Compare and return the maximum of two values.
240 pub fn max<T: TotalOrd>(v1: T, v2: T) -> T {
241 if v1 > v2 { v1 } else { v2 }
246 use super::lexical_ordering;
249 fn test_int_totalord() {
250 assert_eq!(5u.cmp(&10), Less);
251 assert_eq!(10u.cmp(&5), Greater);
252 assert_eq!(5u.cmp(&5), Equal);
253 assert_eq!((-5u).cmp(&12), Less);
254 assert_eq!(12u.cmp(-5), Greater);
258 fn test_ordering_order() {
259 assert!(Less < Equal);
260 assert_eq!(Greater.cmp(&Less), Greater);
264 fn test_lexical_ordering() {
265 fn t(o1: Ordering, o2: Ordering, e: Ordering) {
266 assert_eq!(lexical_ordering(o1, o2), e);
269 let xs = [Less, Equal, Greater];
270 for &o in xs.iter() {
273 t(Greater, o, Greater);
278 fn test_user_defined_eq() {
284 // Our implementation of `Eq` to support `==` and `!=`.
285 impl Eq for SketchyNum {
286 // Our custom eq allows numbers which are near eachother to be equal! :D
287 fn eq(&self, other: &SketchyNum) -> bool {
288 (self.num - other.num).abs() < 5
292 // Now these binary operators will work when applied!
293 assert!(SketchyNum {num: 37} == SketchyNum {num: 34});
294 assert!(SketchyNum {num: 25} != SketchyNum {num: 57});