summaryrefslogtreecommitdiff
path: root/semiring/src/counting.rs
diff options
context:
space:
mode:
authorJSDurand <mmemmew@gmail.com>2023-02-27 12:36:41 +0800
committerJSDurand <mmemmew@gmail.com>2023-02-27 12:36:41 +0800
commitfbaa420ed550e9c3e7cdc09d4a8ec22bfbd782a6 (patch)
treefad9722825bb3fa796dd52c3fd4a8bf46b958cf9 /semiring/src/counting.rs
parentafad02bdff111ecccb0077b9c989e869723c231c (diff)
before a major refactor
I decide to adopt a new approach of recording and updating item derivation forests. Since this affects a lot of things, I decide to commit before the refactor, so that I can create a branch for that refactor.
Diffstat (limited to 'semiring/src/counting.rs')
-rw-r--r--semiring/src/counting.rs43
1 files changed, 43 insertions, 0 deletions
diff --git a/semiring/src/counting.rs b/semiring/src/counting.rs
new file mode 100644
index 0000000..9095888
--- /dev/null
+++ b/semiring/src/counting.rs
@@ -0,0 +1,43 @@
+//! This module implements the "counting semiring", which counts the
+//! number of ways a sentence can be derived by a grammar.
+
+use super::*;
+
+/// The counting semiring is a thin wrapper around the natural numbers
+/// with the usual addition and multiplication.
+#[derive(Copy, Clone, Debug, Ord, PartialOrd, Hash, Eq, PartialEq)]
+pub struct Count(usize);
+
+impl Count {
+ /// Wrap the count in the wrapper.
+ pub fn new(count: usize) -> Self {
+ Self(count)
+ }
+
+ /// Extract the count out.
+ pub fn value(&self) -> usize {
+ self.0
+ }
+}
+
+impl Semiring for Count {
+ fn zero() -> Self {
+ Self::new(0)
+ }
+
+ fn one() -> Self {
+ Self::new(1)
+ }
+
+ fn add(&mut self, other: &Self) {
+ self.0 = self.value() + other.value();
+ }
+
+ fn mul(&mut self, other: &Self) {
+ self.0 = self.value() * other.value();
+ }
+
+ fn valuation(_pos: usize, _grammar: &Grammar) -> Self {
+ Self::new(1)
+ }
+}