Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion src/lax/category.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,26 @@ impl<O: Clone + PartialEq, A: Clone> Arrow for OpenHypergraph<O, A> {
if self.target() != other.source() {
return None;
}
self.lax_compose(other)
}
}

impl<O: Clone + PartialEq, A: Clone> OpenHypergraph<O, A> {
/// Compose two open hypergraphs, unifying the boundary nodes without checking labels.
///
/// Returns None when the boundary arities do not match.
pub fn lax_compose(&self, other: &Self) -> Option<Self> {
if self.targets.len() != other.sources.len() {
return None;
}

let n = self.hypergraph.nodes.len();
let mut f = self.tensor(other);
for (u, v) in self.targets.iter().zip(other.sources.iter()) {
f.unify(*u, NodeId(v.0 + n));
}

f.sources = f.sources[..self.sources.len()].to_vec();
f.sources.truncate(self.sources.len());
f.targets = f.targets[self.targets.len()..].to_vec();

Some(f)
Expand Down
1 change: 1 addition & 0 deletions tests/lax/mod.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
pub mod eval;
pub mod hypergraph;
pub mod open_hypergraph;
47 changes: 47 additions & 0 deletions tests/lax/open_hypergraph.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
use open_hypergraphs::category::Arrow;
use open_hypergraphs::lax::{NodeId, OpenHypergraph};

#[derive(Clone, Debug, PartialEq)]
enum Obj {
A,
B,
C,
}

#[derive(Clone, Debug, PartialEq)]
enum Op {
F,
G,
}

#[test]
fn test_compose_type_mismatch() {
let f = OpenHypergraph::singleton(Op::F, vec![Obj::A], vec![Obj::B]);
let g = OpenHypergraph::singleton(Op::G, vec![Obj::C], vec![Obj::A]);

assert!(Arrow::compose(&f, &g).is_none());
}

#[test]
fn test_lax_compose_allows_mismatch_and_unifies_boundary() {
let f = OpenHypergraph::singleton(Op::F, vec![Obj::A], vec![Obj::B]);
let g = OpenHypergraph::singleton(Op::G, vec![Obj::C], vec![Obj::A]);

let composed = f.lax_compose(&g).expect("arity matches");

assert_eq!(composed.sources, vec![NodeId(0)]);
assert_eq!(composed.targets, vec![NodeId(3)]);
assert_eq!(composed.hypergraph.quotient.0, vec![NodeId(1)]);
assert_eq!(composed.hypergraph.quotient.1, vec![NodeId(2)]);
}

#[test]
fn test_compose_matches_lax_compose_on_equal_boundaries() {
let f = OpenHypergraph::singleton(Op::F, vec![Obj::A], vec![Obj::B]);
let g = OpenHypergraph::singleton(Op::G, vec![Obj::B], vec![Obj::C]);

let strict = Arrow::compose(&f, &g).expect("labels match");
let lax = f.lax_compose(&g).expect("arity matches");

assert_eq!(strict, lax);
}