Skip to content

Instantly share code, notes, and snippets.

alexcrichton/cmp.rs Last active Aug 29, 2015

 pub trait Eq { fn eq(&self, other: &Self) -> bool; } // equality operators are wired to this trait #[lang = "partial_eq"] pub trait PartialEq { fn eq(&self, other: &Self) -> bool; fn ne(&self, other: &Self) -> bool { !self.eq(other) } } pub trait Ord { fn cmp(&self, other: &Self) -> bool; fn lt(&self, other: &Self) -> bool { self.cmp(other) == Less } fn le(&self, other: &Self) -> bool { !other.lt(self) } fn gt(&self, other: &Self) -> bool { other.lt(self) } fn ge(&self, other: &Self) -> bool { !self.lt(other) } } // all comparison operators are wired to this trait #[lang = "partial_ord"] pub trait PartialOrd { fn lt(&self, other: &Self) -> bool; fn le(&self, other: &Self) -> bool { !other.lt(self) } fn gt(&self, other: &Self) -> bool { other.lt(self) } fn ge(&self, other: &Self) -> bool { !self.lt(other) } } impl PartialEq for T { fn eq(&self, other: &T) -> bool { Eq::eq(self, other) } fn ne(&self, other: &T) -> bool { !Eq::eq(self, other) } } impl PartialOrd for T { fn lt(&self, other: &T) -> bool { Ord::lt(self, other) } fn le(&self, other: &T) -> bool { Ord::le(self, other) } fn gt(&self, other: &T) -> bool { Ord::gt(self, other) } fn ge(&self, other: &T) -> bool { Ord::ge(self, other) } }
 // Bar implements Eq/Ord/PartialEq/PartialOrd // // The deriving code only derives an Ord and Eq implementaion, *not* PartialEq or PartialOrd #[deriving(Eq, Ord)] pub struct Bar(int); // Foo implements Eq/Ord/PartialEq/PartialOrd pub struct Foo(int); impl Eq for Foo { fn eq(&self, other: &Foo) -> bool { self.a == other.a } } impl Ord for Foo { fn cmp(&self, other: &Foo) -> Ordering { self.a.cmp(&other.a) } } // Baz implements PartialEq/PartialOrd pub struct Baz { x: f64 } impl PartialEq for Baz { fn eq(&self, other: &Baz) -> bool { self.x == other.x } } impl PartialOrd for Baz { fn lt(&self, other: &Baz) -> bool { self.x < other.x } } // Baz2 implements PartialEq/PartialOrd #[deriving(PartialEq, PartialOrd)] pub struct Baz2 { x: f64 }
 // Works because Eq implies PartialEq fn foo1(t1: &T, t2: &T) { t1 == t2 } // Works because == is wired to PartialEq fn foo2(t1: &T, t2: &T) { t1 == t2 } // Works because Ord implies PartialOrd fn foo3(t1: &T, t2: &T) { t1 < t2 } // Works because < is wired to PartialOrd fn foo4(t1: &T, t2: &T) { t1 < t2 }
to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.