Add NumCast trait for generic numeric type casts

This commit is contained in:
Brendan Zabarauskas 2013-02-11 12:33:05 +11:00
parent 0f04df8522
commit 48b2141b83
24 changed files with 1041 additions and 88 deletions

View file

@ -11,16 +11,16 @@
// except according to those terms.
use cmp::{Eq, Ord};
use num::Num::from_int;
use num::NumCast::from;
extern mod std;
use std::cmp::FuzzyEq;
pub trait NumExt: Num Eq Ord {}
pub trait NumExt: Num NumCast Eq Ord {}
pub trait FloatExt: NumExt FuzzyEq<Self> {}
fn greater_than_one<T:NumExt>(n: &T) -> bool { *n > from_int(1) }
fn greater_than_one_float<T:FloatExt>(n: &T) -> bool { *n > from_int(1) }
fn greater_than_one<T:NumExt>(n: &T) -> bool { *n > from(1) }
fn greater_than_one_float<T:FloatExt>(n: &T) -> bool { *n > from(1) }
pub fn main() {}

View file

@ -12,17 +12,17 @@
// Extending Num and using inherited static methods
use Num::from_int;
use num::NumCast::from;
trait Num {
static fn from_int(i: int) -> Self;
fn gt(&self, other: &Self) -> bool;
}
pub trait NumExt: Num { }
pub trait NumExt: Num NumCast { }
fn greater_than_one<T:NumExt>(n: &T) -> bool {
n.gt(&from_int(1))
n.gt(&from(1))
}
pub fn main() {}

View file

@ -11,12 +11,12 @@
// Using the real Num from core
use cmp::Ord;
use num::Num::from_int;
use num::NumCast::from;
pub trait NumExt: Num Ord { }
pub trait NumExt: Num NumCast Ord { }
fn greater_than_one<T:NumExt>(n: &T) -> bool {
*n > from_int(1)
*n > from(1)
}
pub fn main() {}

View file

@ -13,7 +13,7 @@
// A more complex example of numeric extensions
use cmp::{Eq, Ord};
use num::Num::from_int;
use num::NumCast::from;
extern mod std;
use std::cmp::FuzzyEq;
@ -38,7 +38,7 @@ pub impl f64: TypeExt {}
pub impl float: TypeExt {}
pub trait NumExt: TypeExt Eq Ord Num {}
pub trait NumExt: TypeExt Eq Ord Num NumCast {}
pub impl u8: NumExt {}
pub impl u16: NumExt {}

View file

@ -9,13 +9,13 @@
// except according to those terms.
use cmp::{Eq, Ord};
use num::Num::from_int;
use num::NumCast::from;
pub trait NumExt: Eq Ord Num {}
pub trait NumExt: Eq Ord Num NumCast {}
pub impl f32: NumExt {}
fn num_eq_one<T:NumExt>(n: T) { io::println(fmt!("%?", n == from_int(1))) }
fn num_eq_one<T:NumExt>(n: T) { io::println(fmt!("%?", n == from(1))) }
pub fn main() {
num_eq_one(1f32); // you need to actually use the function to trigger the ICE

View file

@ -9,15 +9,15 @@
// except according to those terms.
use cmp::{Eq, Ord};
use num::Num::from_int;
use num::NumCast::from;
pub trait NumExt: Eq Num {}
pub trait NumExt: Eq Num NumCast {}
pub impl f32: NumExt {}
pub impl int: NumExt {}
fn num_eq_one<T:NumExt>() -> T {
from_int(1)
from(1)
}
pub fn main() {