From b7aedb5b3f5fe964a775ad013a6afa4faa4af02d Mon Sep 17 00:00:00 2001 From: Michael Neumann Date: Sun, 7 Apr 2019 14:44:34 +0200 Subject: [PATCH] Add WeightNum#{add_if_valid, sub_if_valid) and use them --- src/weight_matrix.rs | 6 +++--- src/weight_num.rs | 14 ++++++++++++++ 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/src/weight_matrix.rs b/src/weight_matrix.rs index 233ec85..1580b2e 100644 --- a/src/weight_matrix.rs +++ b/src/weight_matrix.rs @@ -31,14 +31,14 @@ impl Weights for WeightMatrix { fn add_row(&mut self, row: usize, val: T) { self.c .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`. fn sub_column(&mut self, col: usize, val: T) { self.c .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 { @@ -81,7 +81,7 @@ impl WeightMatrix { fn sub_row(&mut self, row: usize, val: T) { self.c .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] { diff --git a/src/weight_num.rs b/src/weight_num.rs index 57b37ef..2faeef5 100644 --- a/src/weight_num.rs +++ b/src/weight_num.rs @@ -6,6 +6,20 @@ pub trait WeightNum: PartialOrd + Copy + Sub + Add fn is_valid(&self) -> bool { 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 {