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
use crate::constraints::TwoOfThree;
use crate::goals::Goal;
use crate::{
    constraints::{Constraint, ResolveFn, VarWatch},
    core::{State, Unify, Value},
};
use std::fmt::{self, Debug};
use std::rc::Rc;

/** Create a [projection goal](super) that allows deriving one resolved value
from the other two.

Functions must be provided to derive from any combination of two values.
Whichever two are resolved first will be used to derive the other.

```
use canrun::{LVar, Query};
use canrun::goals::{map_2, all, unify};

let (x, y, z) = (LVar::new(), LVar::new(), LVar::new());
let goal = all![
    unify(1, x),
    unify(2, y),
    map_2(x, y, z, |x, y| x + y, |x, z| z - x, |y, z| z - y),
];
let result: Vec<_> = goal.query(z).collect();
assert_eq!(result, vec![3])
```
*/
pub fn map_2<A, IA, B, IB, C, IC, ABtoC, ACtoB, BCtoA>(
    a: IA,
    b: IB,
    c: IC,
    ab_to_c: ABtoC,
    ac_to_b: ACtoB,
    bc_to_a: BCtoA,
) -> Map2<A, B, C>
where
    A: Unify,
    B: Unify,
    C: Unify,
    IA: Into<Value<A>>,
    IB: Into<Value<B>>,
    IC: Into<Value<C>>,
    ABtoC: Fn(&A, &B) -> C + 'static,
    ACtoB: Fn(&A, &C) -> B + 'static,
    BCtoA: Fn(&B, &C) -> A + 'static,
{
    Map2 {
        a: a.into(),
        b: b.into(),
        c: c.into(),
        ab_to_c: Rc::new(ab_to_c),
        ac_to_b: Rc::new(ac_to_b),
        bc_to_a: Rc::new(bc_to_a),
    }
}

/** A [projection goal](super) that allows deriving one resolved value
from the other two. Create with [`map_2`].
*/
#[allow(clippy::type_complexity)]
pub struct Map2<A: Unify, B: Unify, C: Unify> {
    a: Value<A>,
    b: Value<B>,
    c: Value<C>,
    ab_to_c: Rc<dyn Fn(&A, &B) -> C>,
    ac_to_b: Rc<dyn Fn(&A, &C) -> B>,
    bc_to_a: Rc<dyn Fn(&B, &C) -> A>,
}

impl<A: Unify, B: Unify, C: Unify> Debug for Map2<A, B, C> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Map2 {:?} {:?} {:?}", self.a, self.b, self.c)
    }
}

impl<A: Unify, B: Unify, C: Unify> Clone for Map2<A, B, C> {
    fn clone(&self) -> Self {
        Self {
            a: self.a.clone(),
            b: self.b.clone(),
            c: self.c.clone(),
            ab_to_c: self.ab_to_c.clone(),
            ac_to_b: self.ac_to_b.clone(),
            bc_to_a: self.bc_to_a.clone(),
        }
    }
}

impl<A: Unify, B: Unify, C: Unify> Goal for Map2<A, B, C> {
    fn apply(&self, state: State) -> Option<State> {
        state.constrain(Rc::new(self.clone()))
    }
}

impl<A: Unify, B: Unify, C: Unify> Constraint for Map2<A, B, C> {
    fn attempt(&self, state: &State) -> Result<ResolveFn, VarWatch> {
        let resolved = TwoOfThree::resolve(&self.a, &self.b, &self.c, state)?;
        match resolved {
            TwoOfThree::AB(a, b, c) => {
                let f = self.ab_to_c.clone();
                Ok(Box::new(move |state| {
                    state.unify(&Value::new(f(&*a, &*b)), &c)
                }))
            }
            TwoOfThree::BC(a, b, c) => {
                let f = self.bc_to_a.clone();
                Ok(Box::new(move |state| {
                    state.unify(&Value::new(f(&*b, &*c)), &a)
                }))
            }
            TwoOfThree::AC(a, b, c) => {
                let f = self.ac_to_b.clone();
                Ok(Box::new(move |state| {
                    state.unify(&Value::new(f(&*a, &*c)), &b)
                }))
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::map_2;
    use crate::core::{LVar, Query};
    use crate::goals::both::both;
    use crate::goals::unify;

    #[test]
    fn succeeds() {
        let x = LVar::new();
        let y = LVar::new();
        let z = LVar::new();
        let goal = both(
            both(both(unify(1, x), unify(2, y)), unify(3, z)),
            map_2(x, y, z, |x, y| x + y, |x, z| z - x, |y, z| z - y),
        );
        assert_eq!(goal.query((x, y)).collect::<Vec<_>>(), vec![(1, 2)]);
    }
}