Skip to content

Instantly share code, notes, and snippets.

@SiegeLord
Created June 11, 2014 15:54
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SiegeLord/f1af81195df89ec04d10 to your computer and use it in GitHub Desktop.
Save SiegeLord/f1af81195df89ec04d10 to your computer and use it in GitHub Desktop.
Rust matrix expression templates
clone
Matrix { data: [100, 200, 300] }
#[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