Saturday, August 02, 2014

A simple Rust `pow` function for the built-in numeric types


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: