use super::Goal;
use crate::core::State;
#[derive(Debug)]
pub struct All {
goals: Vec<Box<dyn Goal>>,
}
impl From<Vec<Box<dyn Goal>>> for All {
fn from(goals: Vec<Box<dyn Goal>>) -> Self {
All { goals }
}
}
impl FromIterator<Box<dyn Goal>> for All {
fn from_iter<T: IntoIterator<Item = Box<dyn Goal>>>(iter: T) -> Self {
All {
goals: iter.into_iter().collect(),
}
}
}
impl Goal for All {
fn apply(&self, state: State) -> Option<State> {
self.goals.iter().try_fold(state, |s, g| g.apply(s))
}
}
#[macro_export]
macro_rules! all {
($($item:expr),* $(,)?) => {
{
let goals: Vec<Box<dyn $crate::goals::Goal>> = vec![$(Box::new($item)),*];
$crate::goals::All::from(goals)
}
};
}
pub use all;
#[cfg(test)]
mod tests {
use crate::{core::LVar, core::Query, goals::unify};
use super::all;
#[test]
fn succeeds() {
let x = LVar::new();
let y = LVar::new();
let goal = all![unify(y, x), unify(y, 1)];
let result = goal.query((x, y)).collect::<Vec<_>>();
assert_eq!(result, vec![(1, 1)]);
}
#[test]
fn fails() {
let x = LVar::new();
let goal = all![unify(x, 5), unify(x, 7)];
let result = goal.query(x).collect::<Vec<_>>();
assert_eq!(result, vec![]);
}
}