num: implement `Hash` for `Complex` and `Ratio`

This commit is contained in:
Vinzent Steinberg 2014-08-29 11:24:15 -04:00
parent f6a7ab40e8
commit 8138c3574f
2 changed files with 22 additions and 4 deletions

View File

@ -12,13 +12,13 @@
//! Complex numbers.
use std::fmt;
use std::num::{Zero,One,ToStrRadix};
use std::num::{Zero, One, ToStrRadix};
// FIXME #1284: handle complex NaN & infinity etc. This
// probably doesn't map to C's _Complex correctly.
/// A complex number in Cartesian form.
#[deriving(PartialEq,Clone)]
#[deriving(PartialEq, Clone, Hash)]
pub struct Complex<T> {
/// Real portion of the complex number
pub re: T,
@ -193,7 +193,8 @@ mod test {
#![allow(non_uppercase_statics)]
use super::{Complex64, Complex};
use std::num::{Zero,One,Float};
use std::num::{Zero, One, Float};
use std::hash::hash;
pub static _0_0i : Complex64 = Complex { re: 0.0, im: 0.0 };
pub static _1_0i : Complex64 = Complex { re: 1.0, im: 0.0 };
@ -367,4 +368,14 @@ mod test {
test(-_neg1_1i, "1-1i".to_string());
test(_05_05i, "0.5+0.5i".to_string());
}
#[test]
fn test_hash() {
let a = Complex::new(0i32, 0i32);
let b = Complex::new(1i32, 0i32);
let c = Complex::new(0i32, 1i32);
assert!(hash(&a) != hash(&b));
assert!(hash(&b) != hash(&c));
assert!(hash(&c) != hash(&a));
}
}

View File

@ -21,7 +21,7 @@ use std::num::{Zero, One, ToStrRadix, FromStrRadix};
use bigint::{BigInt, BigUint, Sign, Plus, Minus};
/// Represents the ratio between 2 numbers.
#[deriving(Clone)]
#[deriving(Clone, Hash)]
#[allow(missing_doc)]
pub struct Ratio<T> {
numer: T,
@ -381,6 +381,7 @@ mod test {
use super::{Ratio, Rational, BigRational};
use std::num::{Zero, One, FromStrRadix, FromPrimitive, ToStrRadix};
use std::from_str::FromStr;
use std::hash::hash;
use std::num;
pub static _0 : Rational = Ratio { numer: 0, denom: 1};
@ -728,4 +729,10 @@ mod test {
assert!(! _neg1_2.is_positive());
assert!(! _1_2.is_negative());
}
#[test]
fn test_hash() {
assert!(hash(&_0) != hash(&_1));
assert!(hash(&_0) != hash(&_3_2));
}
}