1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
use std::{iter::repeat, rc::Rc};
use super::Goal;
use crate::core::{Fork, State, StateIter};
#[derive(Debug, Clone)]
pub struct Any {
goals: Vec<Rc<dyn Goal>>,
}
impl From<Vec<Rc<dyn Goal>>> for Any {
fn from(goals: Vec<Rc<dyn Goal>>) -> Self {
Any { goals }
}
}
impl FromIterator<Rc<dyn Goal>> for Any {
fn from_iter<T: IntoIterator<Item = Rc<dyn Goal>>>(iter: T) -> Self {
Any {
goals: iter.into_iter().collect(),
}
}
}
impl Goal for Any {
fn apply(&self, state: State) -> Option<State> {
state.fork(self.clone())
}
}
impl Fork for Any {
fn fork(&self, state: &State) -> StateIter {
let goals = self.goals.clone().into_iter();
let states = repeat(state.clone());
Box::new(goals.zip(states).flat_map(|(g, s)| g.apply(s).into_iter()))
}
}
#[macro_export]
macro_rules! any {
($($item:expr),* $(,)?) => {
{
let goals: Vec<std::rc::Rc<dyn $crate::goals::Goal>> = vec![$(std::rc::Rc::new($item)),*];
$crate::goals::Any::from(goals)
}
};
}
pub use any;
#[cfg(test)]
mod tests {
use crate::{
core::LVar,
core::Query,
goals::{both::both, fail::Fail, unify},
};
use super::any;
#[test]
fn both_succeed() {
let x = LVar::new();
let goal = any![unify(x, 5), unify(x, 7)];
let result = goal.query(x).collect::<Vec<_>>();
assert_eq!(result, vec![5, 7]);
}
#[test]
fn one_succeeds() {
let x = LVar::new();
let goal = any![unify(x, 5), both(Fail, unify(x, 7))];
let result = goal.query(x).collect::<Vec<_>>();
assert_eq!(result, vec![5]);
}
#[test]
fn all_fail() {
let x = LVar::new();
let goal = any![both(Fail, unify(x, 5)), both(Fail, unify(x, 7))];
let result = goal.query(x).collect::<Vec<_>>();
assert_eq!(result, vec![]);
}
}