Automatically box constraints.

Puzzle.add_constraint() now takes a generic (unboxed) constraint,
making it more pleasant to use when adding custom constraints.
This commit is contained in:
David Wang 2017-03-08 07:57:19 +11:00
parent b1b727b38e
commit ddf425efe0
2 changed files with 6 additions and 5 deletions

View File

@ -290,7 +290,9 @@ impl Puzzle {
}
/// Add a constraint to the puzzle solution.
pub fn add_constraint(&mut self, constraint: Box<Constraint>) {
pub fn add_constraint<T>(&mut self, constraint: T)
where T: Constraint + 'static {
let constraint = Box::new(constraint);
let cidx = self.constraints.len();
for &VarToken(idx) in constraint.vars() {
self.wake[idx].insert(cidx);
@ -312,7 +314,7 @@ impl Puzzle {
/// ```
pub fn all_different<'a, I>(&mut self, vars: I)
where I: IntoIterator<Item=&'a VarToken> {
self.add_constraint(Box::new(constraint::AllDifferent::new(vars)));
self.add_constraint(constraint::AllDifferent::new(vars));
}
/// Add an Equality constraint.
@ -328,8 +330,7 @@ impl Puzzle {
/// ```
pub fn equals<L,R>(&mut self, lhs: L, rhs: R)
where L: Into<LinExpr>, R: Into<LinExpr> {
self.add_constraint(Box::new(constraint::Equality::new(
lhs.into() - rhs.into())));
self.add_constraint(constraint::Equality::new(lhs.into() - rhs.into()));
}
/// Find any solution to the given puzzle.

View File

@ -37,7 +37,7 @@ fn make_queens(n: usize) -> (Puzzle, Vec<VarToken>) {
let vars = sys.new_vars_with_candidates_1d(n, &pos);
sys.all_different(&vars);
sys.add_constraint(Box::new(NoDiagonal{ vars: vars.clone() }));
sys.add_constraint(NoDiagonal{ vars: vars.clone() });
(sys, vars)
}