Skip to main content

membership_data/
membership_data.rs

1//! Give each membership a value: how many people of each group belong to each of two
2//! overlapping bodies.
3//!
4//! Run it with `cargo run -p hypergraph-rs --example membership_data`.
5
6use hypergraph_rs::Hypergraph;
7
8fn main() {
9    // The third type is the value a membership carries. Here it is a head count.
10    let mut h: Hypergraph<(), (), u64> = Hypergraph::new();
11
12    // Nodes are groups of people. Edges are the bodies they sit in. The two bodies overlap
13    // in the "teachers" group.
14    h.add_node_to_edge_with_data("council", "teachers", 3)
15        .unwrap();
16    h.add_node_to_edge_with_data("council", "nurses", 2)
17        .unwrap();
18    h.add_node_to_edge_with_data("union", "teachers", 40)
19        .unwrap();
20    h.add_node_to_edge_with_data("union", "drivers", 25)
21        .unwrap();
22
23    // A value can be changed later. A new membership starts at the default, 0.
24    h.set_member_data("council", "nurses", 4).unwrap();
25    h.add_node_to_edge("council", "drivers").unwrap();
26    assert_eq!(h.member_data("council", "drivers"), Some(&0));
27
28    for body in h.edge_ids() {
29        let seats = h.members_with_data(&body).unwrap();
30        let total: u64 = seats.iter().map(|(_, count)| **count).sum();
31        println!("{body}: {seats:?}, {total} people in all");
32    }
33
34    let council: u64 = h
35        .members_with_data("council")
36        .unwrap()
37        .iter()
38        .map(|(_, count)| **count)
39        .sum();
40    let union: u64 = h
41        .members_with_data("union")
42        .unwrap()
43        .iter()
44        .map(|(_, count)| **count)
45        .sum();
46    assert_eq!(council, 3 + 4);
47    assert_eq!(union, 40 + 25);
48
49    // The same group holds a different value in each body.
50    assert_eq!(h.member_data("council", "teachers"), Some(&3));
51    assert_eq!(h.member_data("union", "teachers"), Some(&40));
52}