Impl comp_add and comp_mul using Array::zip

This commit is contained in:
Brendan Zabarauskas 2013-09-14 10:54:19 +10:00
parent 28dd7963ba
commit 00db4f17b4
2 changed files with 15 additions and 9 deletions

View file

@ -50,6 +50,8 @@ pub trait Array
V: Clone, SliceV, VV: Array<V, SliceV>>(&self, other: &UU, f: &fn(&T, &U) -> V) -> VV {
Array::build(|i| f(self.i(i), other.i(i)))
}
fn zip(&self, f: &fn(&T, &T) -> T) -> T;
}
macro_rules! array(
@ -94,17 +96,27 @@ macro_rules! array(
fn mut_iter<'a>(&'a mut self) -> ::std::vec::VecMutIterator<'a, $T> {
self.as_mut_slice().mut_iter()
}
#[inline]
fn zip(&self, f: &fn(&$T, &$T) -> $T) -> $T {
gen_zip!($_n)
}
}
)
)
macro_rules! gen_builder(
(_1) => ([builder(0)]);
(_2) => ([builder(0), builder(1)]);
(_3) => ([builder(0), builder(1), builder(2)]);
(_4) => ([builder(0), builder(1), builder(2), builder(3)]);
)
macro_rules! gen_zip(
(_2) => (f(self.i(0), self.i(1)));
(_3) => (f(&f(self.i(0), self.i(1)), self.i(2)));
(_4) => (f(&f(&f(self.i(0), self.i(1)), self.i(2)), self.i(3)));
)
macro_rules! approx_eq(
(impl<$S:ident> $Self:ty) => (
impl<$S: Clone + ApproxEq<$S>> ApproxEq<$S> for $Self {

View file

@ -130,10 +130,10 @@ pub trait Vector
#[inline] fn rem_self_v(&mut self, other: &Self);
/// The sum of each component of the vector.
#[inline] fn comp_add(&self) -> S;
#[inline] fn comp_add(&self) -> S { self.zip(|a, b| a.add(b)) }
/// The product of each component of the vector.
#[inline] fn comp_mul(&self) -> S;
#[inline] fn comp_mul(&self) -> S { self.zip(|a, b| a.mul(b)) }
/// Vector dot product.
#[inline] fn dot(&self, other: &Self) -> S { self.mul_v(other).comp_add() }
@ -181,12 +181,6 @@ macro_rules! vector(
#[inline] fn mul_self_v(&mut self, other: &$Self<$S>) { self.$x = self.$x.mul(&other.$x); $(self.$xs = self.$xs.mul(&other.$xs);)+ }
#[inline] fn div_self_v(&mut self, other: &$Self<$S>) { self.$x = self.$x.div(&other.$x); $(self.$xs = self.$xs.div(&other.$xs);)+ }
#[inline] fn rem_self_v(&mut self, other: &$Self<$S>) { self.$x = self.$x.rem(&other.$x); $(self.$xs = self.$xs.rem(&other.$xs);)+ }
/// The sum of each component of the vector.
#[inline] fn comp_add(&self) -> S { self.$x $(.add(&self.$xs))+ }
/// The product of each component of the vector.
#[inline] fn comp_mul(&self) -> S { self.$x $(.mul(&self.$xs))+ }
}
)
)