From 442e5423479608e417011a1cd34e9a304eda8153 Mon Sep 17 00:00:00 2001 From: Guillaume Pinot Date: Wed, 15 Sep 2021 17:37:20 +0200 Subject: [PATCH] Convert an iterator of Into to a LinearExpr --- Cargo.toml | 2 +- src/builder.rs | 20 ++++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index a769ec6..368bda5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "cp_sat" -version = "0.3.1" +version = "0.3.2" edition = "2018" description = "Rust bindings to the Google CP-SAT constraint programming solver." documentation = "https://docs.rs/cp_sat" diff --git a/src/builder.rs b/src/builder.rs index 7b63ee7..5cc2c1e 100644 --- a/src/builder.rs +++ b/src/builder.rs @@ -877,6 +877,11 @@ pub struct Constraint(usize); /// _ => expr -= LinearExpr::from([(42, v), (1337, y1)]) + 5, /// } /// } +/// +/// // an iterator of `Into` can be collected or extended, +/// // meaning summing the elements +/// model.maximize(vars.iter().copied().collect::()); // means sum(vars) +/// expr.extend(vars.iter().map(|&v| (2, v))); // means expr += sum_vars(2 * v) /// ``` #[derive(Clone, Default, Debug)] pub struct LinearExpr { @@ -974,3 +979,18 @@ impl From for proto::LinearExpressionProto { } } } + +impl> std::iter::Extend for LinearExpr { + fn extend>(&mut self, iter: I) { + for e in iter { + *self += e; + } + } +} +impl> std::iter::FromIterator for LinearExpr { + fn from_iter>(iter: I) -> Self { + let mut res = LinearExpr::default(); + res.extend(iter); + res + } +}