Add WeightNum#{add_if_valid, sub_if_valid) and use them

This commit is contained in:
Michael Neumann 2019-04-07 14:44:34 +02:00
parent fe2d4bb8af
commit b7aedb5b3f
2 changed files with 17 additions and 3 deletions

View File

@ -31,14 +31,14 @@ impl<T: WeightNum> Weights for WeightMatrix<T> {
fn add_row(&mut self, row: usize, val: T) { fn add_row(&mut self, row: usize, val: T) {
self.c self.c
.row_mut(row) .row_mut(row)
.mapv_inplace(|cur| if cur.is_valid() { cur + val } else { cur }); .mapv_inplace(|cur| cur.add_if_valid(val));
} }
// Subtract `val` from every element in column `col`. // Subtract `val` from every element in column `col`.
fn sub_column(&mut self, col: usize, val: T) { fn sub_column(&mut self, col: usize, val: T) {
self.c self.c
.column_mut(col) .column_mut(col)
.mapv_inplace(|cur| if cur.is_valid() { cur - val } else { cur }); .mapv_inplace(|cur| cur.sub_if_valid(val));
} }
fn is_solvable(&self) -> bool { fn is_solvable(&self) -> bool {
@ -81,7 +81,7 @@ impl<T: WeightNum> WeightMatrix<T> {
fn sub_row(&mut self, row: usize, val: T) { fn sub_row(&mut self, row: usize, val: T) {
self.c self.c
.row_mut(row) .row_mut(row)
.mapv_inplace(|cur| if cur.is_valid() { cur - val } else { cur }); .mapv_inplace(|cur| cur.sub_if_valid(val));
} }
pub fn as_slice(&self) -> &[T] { pub fn as_slice(&self) -> &[T] {

View File

@ -6,6 +6,20 @@ pub trait WeightNum: PartialOrd + Copy + Sub<Output = Self> + Add<Output = Self>
fn is_valid(&self) -> bool { fn is_valid(&self) -> bool {
true true
} }
fn add_if_valid(self, other: Self) -> Self {
if self.is_valid() {
self + other
} else {
self
}
}
fn sub_if_valid(self, other: Self) -> Self {
if self.is_valid() {
self - other
} else {
self
}
}
} }
impl WeightNum for usize { impl WeightNum for usize {