From 8cec9d495dab6086fbefa96b8c27ae8e24b0df49 Mon Sep 17 00:00:00 2001 From: Paolo Falabella Date: Fri, 4 Jul 2014 17:48:58 +0100 Subject: [PATCH] Added num::Signed implementation to Ratio (squashed) --- src/libnum/rational.rs | 44 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/src/libnum/rational.rs b/src/libnum/rational.rs index c35b2976b40..1792f282eca 100644 --- a/src/libnum/rational.rs +++ b/src/libnum/rational.rs @@ -15,6 +15,7 @@ use Integer; use std::cmp; use std::fmt; use std::from_str::FromStr; +use std::num; use std::num::{Zero, One, ToStrRadix, FromStrRadix}; use bigint::{BigInt, BigUint, Sign, Plus, Minus}; @@ -273,6 +274,36 @@ impl impl Num for Ratio {} +impl + num::Signed for Ratio { + #[inline] + fn abs(&self) -> Ratio { + if self.is_negative() { -self.clone() } else { self.clone() } + } + + #[inline] + fn abs_sub(&self, other: &Ratio) -> Ratio { + if *self <= *other { Zero::zero() } else { *self - *other } + } + + #[inline] + fn signum(&self) -> Ratio { + if *self > Zero::zero() { + num::one() + } else if self.is_zero() { + num::zero() + } else { + - num::one::>() + } + } + + #[inline] + fn is_positive(&self) -> bool { *self > Zero::zero() } + + #[inline] + fn is_negative(&self) -> bool { *self < Zero::zero() } +} + /* String conversions */ impl fmt::Show for Ratio { /// Renders as `numer/denom`. If denom=1, renders as numer. @@ -338,6 +369,7 @@ mod test { use super::{Ratio, Rational, BigRational}; use std::num::{Zero, One, FromStrRadix, FromPrimitive, ToStrRadix}; use std::from_str::FromStr; + use std::num; pub static _0 : Rational = Ratio { numer: 0, denom: 1}; pub static _1 : Rational = Ratio { numer: 1, denom: 1}; @@ -672,4 +704,16 @@ mod test { assert_eq!(Ratio::from_float(f64::INFINITY), None); assert_eq!(Ratio::from_float(f64::NEG_INFINITY), None); } + + #[test] + fn test_signed() { + assert_eq!(_neg1_2.abs(), _1_2); + assert_eq!(_3_2.abs_sub(&_1_2), _1); + assert_eq!(_1_2.abs_sub(&_3_2), Zero::zero()); + assert_eq!(_1_2.signum(), One::one()); + assert_eq!(_neg1_2.signum(), - num::one::>()); + assert!(_neg1_2.is_negative()); + assert!(! _neg1_2.is_positive()); + assert!(! _1_2.is_negative()); + } }