While playing with Rust I wrote a simple pow
function:
fn pow<T: Num + FromPrimitive + Copy>(a: T, mut b: uint) -> T {
if b == 0 {
return FromPrimitive::from_int(1)
.expect("1 must be convertible to type of a");
}
let mut m: T = a;
b -= 1;
while b != 0 {
m = m * a;
b -= 1;
}
return m;
}
Here is a link to the playpen where you can test it out: http://is.gd/JBWtVf
No comments:
Post a Comment