Add one-dimensional primitives.

This commit is contained in:
Sébastien Crozet 2013-05-16 21:43:14 +00:00
parent d636fdd346
commit e11cbb0963
2 changed files with 158 additions and 0 deletions

94
src/dim1/mat1.rs Normal file
View File

@ -0,0 +1,94 @@
use core::num::{One, Zero};
use traits::dim::Dim;
use traits::inv::Inv;
use traits::transpose::Transpose;
use traits::workarounds::rlmul::{RMul, LMul};
use dim1::vec1::Vec1;
#[deriving(Eq)]
pub struct Mat1<T>
{ m11: T }
pub fn Mat1<T:Copy>(m11: T) -> Mat1<T>
{
Mat1
{ m11: m11 }
}
impl<T> Dim for Mat1<T>
{
fn dim() -> uint
{ 1 }
}
impl<T:Copy + One> One for Mat1<T>
{
fn one() -> Mat1<T>
{ return Mat1(One::one()) }
}
impl<T:Copy + Zero> Zero for Mat1<T>
{
fn zero() -> Mat1<T>
{ Mat1(Zero::zero()) }
fn is_zero(&self) -> bool
{ self.m11.is_zero() }
}
impl<T:Copy + Mul<T, T> + Add<T, T>> Mul<Mat1<T>, Mat1<T>> for Mat1<T>
{
fn mul(&self, other: &Mat1<T>) -> Mat1<T>
{ Mat1 (self.m11 * other.m11) }
}
impl<T:Copy + Add<T, T> + Mul<T, T>> RMul<Vec1<T>> for Mat1<T>
{
fn rmul(&self, other: &Vec1<T>) -> Vec1<T>
{ Vec1(self.m11 * other.x) }
}
impl<T:Copy + Add<T, T> + Mul<T, T>> LMul<Vec1<T>> for Mat1<T>
{
fn lmul(&self, other: &Vec1<T>) -> Vec1<T>
{ Vec1(self.m11 * other.x) }
}
impl<T:Copy + Mul<T, T> + Quot<T, T> + Sub<T, T> + Neg<T> + Zero + One>
Inv for Mat1<T>
{
fn inverse(&self) -> Mat1<T>
{
let mut res : Mat1<T> = *self;
res.invert();
res
}
fn invert(&mut self)
{
assert!(!self.m11.is_zero());
self.m11 = One::one::<T>() / self.m11
}
}
impl<T:Copy> Transpose for Mat1<T>
{
fn transposed(&self) -> Mat1<T>
{ *self }
fn transpose(&mut self)
{ }
}
impl<T:ToStr> ToStr for Mat1<T>
{
fn to_str(&self) -> ~str
{
~"Mat1 {"
+ " m11: " + self.m11.to_str()
+ " }"
}
}

64
src/dim1/vec1.rs Normal file
View File

@ -0,0 +1,64 @@
use core::num::{Zero, Algebraic};
use traits::dot::Dot;
use traits::dim::Dim;
#[deriving(Eq)]
pub struct Vec1<T>
{ x : T }
pub fn Vec1<T:Copy>(x: T) -> Vec1<T>
{ Vec1 {x: x} }
impl<T> Dim for Vec1<T>
{
fn dim() -> uint
{ 1 }
}
impl<T:Copy + Add<T,T>> Add<Vec1<T>, Vec1<T>> for Vec1<T>
{
fn add(&self, other: &Vec1<T>) -> Vec1<T>
{ Vec1(self.x + other.x) }
}
impl<T:Copy + Sub<T,T>> Sub<Vec1<T>, Vec1<T>> for Vec1<T>
{
fn sub(&self, other: &Vec1<T>) -> Vec1<T>
{ Vec1(self.x - other.x) }
}
impl<T:Copy + Mul<T, T> + Add<T, T> + Algebraic> Dot<T> for Vec1<T>
{
fn dot(&self, other : &Vec1<T>) -> T
{ self.x * other.x }
fn sqnorm(&self) -> T
{ self.dot(self) }
fn norm(&self) -> T
{ self.sqnorm().sqrt() }
}
impl<T:Copy + Neg<T>> Neg<Vec1<T>> for Vec1<T>
{
fn neg(&self) -> Vec1<T>
{ Vec1(-self.x) }
}
impl<T:Copy + Zero> Zero for Vec1<T>
{
fn zero() -> Vec1<T>
{
let _0 = Zero::zero();
Vec1(_0)
}
fn is_zero(&self) -> bool
{ self.x.is_zero() }
}
impl<T:ToStr> ToStr for Vec1<T>
{
fn to_str(&self) -> ~str
{ ~"Vec1 { x : " + self.x.to_str() + " }" }
}