Skip to content

Commit

Permalink
Improve lp_sum
Browse files Browse the repository at this point in the history
Fixes #65
Fixes #41
Helps with #37
  • Loading branch information
lovasoa committed Feb 10, 2021
1 parent 4c08382 commit 7293e97
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 8 deletions.
19 changes: 14 additions & 5 deletions src/dsl/variables.rs
Original file line number Diff line number Diff line change
Expand Up @@ -462,12 +462,21 @@ pub fn simplify(expr: &LpExpression) -> LpExpression {
/// problem += lp_sum(v).equal(10.0);
/// ```
///
pub fn lp_sum<T>(expr: &Vec<T>) -> LpExpression where T: Into<LpExpression> + Clone {
if let Some(first) = expr.first() {
expr[1..].iter().fold(first.clone().into(), |a,b| AddExpr(Box::new(a), Box::new(b.clone().into())) )
} else {
panic!("vector should have at least one element");
pub fn lp_sum<T>(expr: &Vec<T>) -> LpExpression
where T: Into<LpExpression> + Clone {
let mut results: Vec<LpExpression> = expr.iter().map(|e| e.clone().into()).collect();
let mut next = Vec::with_capacity(results.len() / 2);
while results.len() > 1 {
while results.len() >= 2 {
let right = results.pop().expect("impossible because len>2");
let left = results.pop().expect("impossible because len>2");
next.push(left + right)
}
next.append(&mut results);
next.reverse(); // Required only if we want to maintain the order of operations
std::mem::swap(&mut results, &mut next)
}
results.into_iter().next().unwrap_or(LitVal(0.))
}

pub fn sum<'a, T: 'a,U>(expr: &'a Vec<T>, f: impl Fn(&'a T) -> U) -> LpExpression where U: Into<LpExpression> + Clone {
Expand Down
7 changes: 4 additions & 3 deletions tests/expression.rs
Original file line number Diff line number Diff line change
Expand Up @@ -187,9 +187,10 @@ fn expression_with_lp_sum() {
lp_sum(expr3).le(5.5).to_lp_file_format(),
"a <= 5.5"
);
assert!(
std::panic::catch_unwind( || lp_sum(empty)).is_err(),
"should panic if empty vec"
assert_eq!(
lp_sum(empty).to_lp_file_format(),
"0",
"should not panic if empty vec"
);
}

Expand Down

0 comments on commit 7293e97

Please sign in to comment.