Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add multiset-sum primitive #471

Merged
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
48 changes: 48 additions & 0 deletions src/sort/multiset.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,14 @@ mod inner {
}
multiset
}

/// Compute the sum of two multisets.
pub fn sum(self, MultiSet(other_map, other_count): Self) -> Self {
Self(
self.0.union_with(other_map, std::ops::Add::add),
self.1 + other_count,
)
}
}
}

Expand Down Expand Up @@ -130,6 +138,7 @@ impl Presort for MultiSetSort {
"multiset-not-contains".into(),
"multiset-remove".into(),
"multiset-length".into(),
"multiset-sum".into(),
"unstable-multiset-map".into(),
]
}
Expand Down Expand Up @@ -233,6 +242,10 @@ impl Sort for MultiSetSort {
name: "multiset-pick".into(),
multiset: self.clone(),
});
typeinfo.add_primitive(Sum {
name: "multiset-sum".into(),
multiset: self.clone(),
});
let inner_name = self.element.name();
let fn_sort = typeinfo.get_sort_by(|s: &Arc<FunctionSort>| {
(s.output.name() == inner_name)
Expand Down Expand Up @@ -535,6 +548,41 @@ impl PrimitiveLike for Pick {
}
}

struct Sum {
name: Symbol,
multiset: Arc<MultiSetSort>,
}

impl PrimitiveLike for Sum {
fn name(&self) -> Symbol {
self.name
}

fn get_type_constraints(&self, span: &Span) -> Box<dyn TypeConstraint> {
SimpleTypeConstraint::new(
self.name(),
vec![
self.multiset.clone(),
self.multiset.clone(),
self.multiset.clone(),
],
span.clone(),
)
.into_box()
}

fn apply(
&self,
values: &[Value],
_sorts: (&[ArcSort], &ArcSort),
_egraph: Option<&mut EGraph>,
) -> Option<Value> {
let lhs_multiset = ValueMultiSet::load(&self.multiset, &values[0]);
let rhs_multiset = ValueMultiSet::load(&self.multiset, &values[1]);
lhs_multiset.sum(rhs_multiset).store(&self.multiset)
}
}

struct Map {
name: Symbol,
multiset: Arc<MultiSetSort>,
Expand Down
12 changes: 12 additions & 0 deletions tests/multiset.egg
Original file line number Diff line number Diff line change
Expand Up @@ -56,3 +56,15 @@
(multiset-of (Num 1) (Num 4) (Num 9))
squared-xs
))

;; sum
(check (=
(multiset-sum (multiset-of (Num 1) (Num 2) (Num 3)) (multiset-of (Num 1) (Num 2) (Num 4)))
(multiset-of (Num 1) (Num 4) (Num 2) (Num 3) (Num 2) (Num 1))
))

;; verify that sum computes length
(check (=
(multiset-length (multiset-sum (multiset-of (Num 1) (Num 2) (Num 3)) (multiset-of (Num 1) (Num 2) (Num 4))))
6
))
Loading