adds Key generic parameters, use custom Key type from template.rs

This commit is contained in:
2019-02-10 14:43:18 +01:00
parent 29b2f076bf
commit 2f3993bb9e
11 changed files with 241 additions and 279 deletions

View File

@@ -2,15 +2,16 @@
//!
//! Provides `Variables`, `Domain` structs and `solve_all` function.
use std::fmt;
use std::hash::Hash;
use std::clone::Clone;
use std::collections::HashMap;
/// An assignments map of variables
pub type Variables<'a, V> = HashMap<String, Option<&'a V>>;
pub type Variables<'a, V, K> = HashMap<K, Option<&'a V>>;
enum Assignment<'a, V> {
Update(String, &'a V),
Clear(String)
enum Assignment<'a, V, K> {
Update(K, &'a V),
Clear(K)
}
@@ -38,13 +39,17 @@ impl<V> Domain<V> {
/// # extern crate planner;
/// # use planner::solver::Domain;
/// let domain = Domain::new(vec![1,2,3]);
/// fn even(i: &i32) -> bool { i % 2 == 0 };
/// assert_eq!(&domain.filter(even).values, &vec![2]);
/// fn even(i: &i32) -> bool {
/// i % 2 == 0
/// };
/// assert_eq!(domain.filter(even), vec![&2]);
/// assert_eq!(domain.filter(|i: &i32| i % 2 == 1), vec![&1,&3]);
/// ```
pub fn filter(&self, f: fn(&&V) -> bool) -> DomainValues<V>
where V: std::clone::Clone
{
self.values.iter().filter(f).collect()
pub fn filter(&self, filter_func: fn(&V) -> bool) -> DomainValues<V> {
self.values
.iter()
.filter(|v: &&V| filter_func(*v))
.collect()
}
}
@@ -55,26 +60,31 @@ impl<V: fmt::Debug> fmt::Debug for Domain<V> {
}
pub type Constraint<'a,V> = fn(&Variables<'a,V>) -> bool;
pub type Constraint<'a,V, K> = fn(&Variables<'a,V, K>) -> bool;
pub struct Problem<'a, V> {
pub struct Problem<'a, V, K> {
/// The initial assignements map
variables: Variables<'a, V>,
variables: Variables<'a, V, K>,
/// Each variable has its associated domain
domains: HashMap<String, DomainValues<'a,V>>,
domains: HashMap<K, DomainValues<'a,V>>,
/// Set of constraints to validate
constraints: Vec<Constraint<'a,V>>,
constraints: Vec<Constraint<'a,V,K>>,
}
impl<'a,V> Problem<'a, V> {
impl<'a,V, K: Eq + Hash + Clone> Problem<'a, V, K> {
pub fn build() -> ProblemBuilder<'a,V> {
pub fn build() -> ProblemBuilder<'a,V, K> {
ProblemBuilder::new()
}
pub fn from_template(_template: i32) -> Problem<'a, V, K> {
Self::build()
.finish()
}
/// Returns all possible Updates for next assignements, prepended with
/// a Clear to ensure the variable is unset before when leaving the branch.
fn _push_updates(&self) -> Option<Vec<Assignment<'a,V>>> {
fn _push_updates(&self) -> Option<Vec<Assignment<'a,V, K>>> {
// TODO: should be able to inject a choosing strategy
if let Some((key,_)) = self.variables.iter().find(|(_, val)| val.is_none()) {
let domain_values = self.domains.get(key).expect("No domain for variable !");
@@ -100,12 +110,13 @@ impl<'a,V> Problem<'a, V> {
return true;
}
/// Visit all possible solutions, using a stack (DFS).
pub fn solve_all(&mut self) -> Vec<Variables<'a,V>>
where V: Clone + fmt::Debug
/// Returns all complete solutions, after visiting all possible outcomes using a stack (DFS).
pub fn solve_all(&mut self) -> Vec<Variables<'a,V,K>>
where V: Clone + fmt::Debug,
K: Clone + fmt::Debug,
{
let mut solutions: Vec<Variables<V>> = vec![];
let mut stack: Vec<Assignment<'a, V>> = vec![];
let mut solutions: Vec<Variables<V, K>> = vec![];
let mut stack: Vec<Assignment<'a, V, K>> = vec![];
stack.append(&mut self._push_updates().unwrap());
loop {
let node = stack.pop();
@@ -134,10 +145,10 @@ impl<'a,V> Problem<'a, V> {
}
}
pub struct ProblemBuilder<'a, V>(Problem<'a, V>);
pub struct ProblemBuilder<'a, V, K>(Problem<'a, V, K>);
impl<'a, V> ProblemBuilder<'a, V> {
fn new() -> ProblemBuilder<'a, V> {
impl<'a, V, K: Eq + Hash + Clone> ProblemBuilder<'a, V, K> {
fn new() -> ProblemBuilder<'a, V, K> {
ProblemBuilder(
Problem{
variables: Variables::new(),
@@ -146,21 +157,19 @@ impl<'a, V> ProblemBuilder<'a, V> {
})
}
pub fn add_variable<S>(mut self, name: S, domain: Vec<&'a V>, value: Option<&'a V>) -> Self
where S: Into<String>
pub fn add_variable(mut self, name: K, domain: Vec<&'a V>, value: Option<&'a V>) -> Self
{
let name = name.into();
self.0.variables.insert(name.clone(), value);
self.0.domains.insert(name, domain);
self
}
pub fn add_constraint(mut self, cons: Constraint<'a,V>) -> Self {
pub fn add_constraint(mut self, cons: Constraint<'a,V, K>) -> Self {
self.0.constraints.push(cons);
self
}
pub fn finish(self) -> Problem<'a, V> {
pub fn finish(self) -> Problem<'a, V, K> {
self.0
}
}
@@ -172,15 +181,15 @@ mod tests {
fn test_solver_find_pairs() {
use super::*;
let domain = Domain::new(vec![1,2,3]);
let mut problem: Problem<_> = Problem::build()
let mut problem: Problem<_, _> = Problem::build()
.add_variable(String::from("Left"), domain.all(), None)
.add_variable(String::from("Right"), domain.all(), None)
.add_constraint(|assign: &Variables<i32>| {
.add_constraint(|assign: &Variables<i32, _>| {
assign.get("Left").unwrap() == assign.get("Right").unwrap()
})
.finish();
let solutions: Vec<Variables<i32>> = vec![
let solutions: Vec<Variables<i32, _>> = vec![
[("Left".to_string(), Some(&3)), ("Right".to_string(), Some(&3)),].iter().cloned().collect(),
[("Left".to_string(), Some(&2)), ("Right".to_string(), Some(&2)),].iter().cloned().collect(),
[("Left".to_string(), Some(&1)), ("Right".to_string(), Some(&1)),].iter().cloned().collect(),
@@ -193,15 +202,15 @@ mod tests {
fn test_solver_find_pairs_with_initial() {
use super::*;
let domain = Domain::new(vec![1,2,3]);
let mut problem: Problem<_> = Problem::build()
let mut problem: Problem<_, _> = Problem::build()
.add_variable("Left".to_string(), domain.all(), None)
.add_variable("Right".to_string(), domain.all(), Some(&2))
.add_constraint( |assign: &Variables<i32>| {
.add_constraint( |assign: &Variables<i32, _>| {
assign.get("Left").unwrap() == assign.get("Right").unwrap()
})
.finish();
let solutions: Vec<Variables<i32>> = vec![
let solutions: Vec<Variables<i32, _>> = vec![
[("Left".to_string(), Some(&2)), ("Right".to_string(), Some(&2)),].iter().cloned().collect(),
];