Skip to main content

annotated/
annotated.rs

1//! Deterministic annotated relations with exact support materialization.
2
3use relmath::{
4    UnaryRelation,
5    annotated::{AnnotatedRelation, Semiring},
6};
7
8#[derive(Clone, Copy, Debug, PartialEq, Eq)]
9struct SupportCount(u8);
10
11impl Semiring for SupportCount {
12    fn zero() -> Self {
13        Self(0)
14    }
15
16    fn one() -> Self {
17        Self(1)
18    }
19
20    fn add(&self, rhs: &Self) -> Self {
21        Self(self.0.saturating_add(rhs.0))
22    }
23
24    fn mul(&self, rhs: &Self) -> Self {
25        Self(self.0.saturating_mul(rhs.0))
26    }
27}
28
29fn main() {
30    let confirmations = AnnotatedRelation::from_facts([
31        (("Alice", "Math"), SupportCount(1)),
32        (("Alice", "Math"), SupportCount(1)),
33        (("Bob", "Physics"), SupportCount(1)),
34        (("Cara", "Logic"), SupportCount::zero()),
35    ]);
36
37    let exact_completed = confirmations.to_binary_relation();
38    let alice = UnaryRelation::singleton("Alice");
39
40    assert_eq!(
41        confirmations.annotation_of(&("Alice", "Math")),
42        Some(&SupportCount(2))
43    );
44    assert_eq!(exact_completed.image(&alice).to_vec(), vec!["Math"]);
45    assert!(!confirmations.contains_fact(&("Cara", "Logic")));
46    assert_eq!(
47        confirmations
48            .iter()
49            .map(|(fact, count)| (*fact, count.0))
50            .collect::<Vec<_>>(),
51        vec![(("Alice", "Math"), 2), (("Bob", "Physics"), 1)]
52    );
53
54    println!(
55        "stored support counts: {:?}",
56        confirmations
57            .iter()
58            .map(|(fact, count)| (*fact, count.0))
59            .collect::<Vec<_>>()
60    );
61}