Created
June 11, 2014 15:54
-
-
Save SiegeLord/f1af81195df89ec04d10 to your computer and use it in GitHub Desktop.
Rust matrix expression templates
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
clone | |
Matrix { data: [100, 200, 300] } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[deriving(Show)] | |
struct Matrix | |
{ | |
data: Vec<f32> | |
} | |
// Just so we can signal when we actually make a clone | |
impl Clone for Matrix | |
{ | |
fn clone(&self) -> Matrix | |
{ | |
println!("clone"); | |
Matrix{ data: self.data.clone() } | |
} | |
} | |
#[deriving(Clone)] | |
struct MulOp<T> | |
{ | |
a: T, | |
b: f32 | |
} | |
trait Eval | |
{ | |
fn eval(&self) -> Matrix; | |
} | |
impl<T: Eval> Eval for MulOp<T> | |
{ | |
fn eval(&self) -> Matrix | |
{ | |
let mut m = self.a.eval(); | |
for e in m.data.mut_iter() | |
{ | |
*e *= self.b; | |
} | |
m | |
} | |
} | |
impl<'l> Eval for &'l Matrix | |
{ | |
fn eval(&self) -> Matrix | |
{ | |
(*self).clone() | |
} | |
} | |
impl<'l> Mul<f32, MulOp<&'l Matrix>> for &'l Matrix | |
{ | |
fn mul(&self, b: &f32) -> MulOp<&'l Matrix> | |
{ | |
MulOp{ a: self.clone(), b: *b } | |
} | |
} | |
impl<'l, T: Eval + Clone> Mul<f32, MulOp<MulOp<T>>> for MulOp<T> | |
{ | |
fn mul(&self, b: &f32) -> MulOp<MulOp<T>> | |
{ | |
MulOp{ a: self.clone(), b: *b } | |
} | |
} | |
fn main() | |
{ | |
let m = Matrix{ data: vec![1.0f32, 2.0, 3.0] }; | |
let m2 = (&m * 2.0 * 5.0 * 10.0).eval(); | |
println!("{}", m2); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment