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
use super::LVec;
use crate::{
core::{
constraints::{resolve_2, Constraint, ResolveFn, VarWatch},
State, Unify, Value,
},
goals::Goal,
};
use std::{fmt::Debug, rc::Rc};
#[derive(Debug)]
pub struct Get<T: Unify> {
item: Value<T>,
index: Value<usize>,
collection: Value<LVec<T>>,
}
impl<T: Unify> Clone for Get<T> {
fn clone(&self) -> Self {
Self {
item: self.item.clone(),
index: self.index.clone(),
collection: self.collection.clone(),
}
}
}
pub fn get<T, IntoT, Index, Collection>(item: IntoT, index: Index, collection: Collection) -> Get<T>
where
T: Unify,
IntoT: Into<Value<T>>,
Index: Into<Value<usize>>,
Collection: Into<Value<LVec<T>>>,
{
Get {
item: item.into(),
index: index.into(),
collection: collection.into(),
}
}
impl<T: Unify> Goal for Get<T> {
fn apply(&self, state: State) -> Option<State> {
state.constrain(Rc::new(self.clone()))
}
}
impl<T: Unify> Constraint for Get<T> {
fn attempt(&self, state: &State) -> Result<ResolveFn, VarWatch> {
let (index, collection) = resolve_2(&self.index, &self.collection, state)?;
let item = self.item.clone();
let found = collection.vec.get(*index);
match found {
Some(found) => {
let found: Value<T> = found.clone();
Ok(Box::new(move |state| state.unify(&item, &found)))
}
None => Ok(Box::new(|_| None)), }
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{core::LVar, core::Query, lvec};
#[test]
fn basic_get() {
let x = LVar::new();
let goal = get(x, 0, lvec![1, 2, 3]);
assert_eq!(goal.query(x).collect::<Vec<_>>(), vec![1]);
}
#[test]
fn get_with_lh_var() {
let x = LVar::new();
let goal = get(x, 1, lvec![1, 2, 3]);
assert_eq!(goal.query(x).collect::<Vec<_>>(), vec![2]);
}
#[test]
fn get_with_rh_var() {
let x = LVar::new();
let goal = get(3, 2, lvec![1, 2, x]);
assert_eq!(goal.query(x).collect::<Vec<_>>(), vec![3]);
}
#[test]
fn get_fails() {
let x = LVar::new();
let goal = get(x, 3, lvec![1, 2]);
assert_eq!(goal.query(x).collect::<Vec<_>>(), vec![] as Vec<i32>);
}
}