Skip to content

Commit

Permalink
Add RationalSemiring with the rational crate
Browse files Browse the repository at this point in the history
Part of: #155
  • Loading branch information
mattxwang committed Jul 24, 2023
1 parent af20185 commit c3114ed
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 0 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ segment-tree = "2.0.0"
bumpalo = "3.11.1"
petgraph = "0.6.2"
rand_chacha = "0.3.1"
rational = "1.2.2"
# optional: only used to build [[bin]]
clap = { version = "4.2.1", features = ["derive"], optional = true }
serde_json = { version = "1.0.81", optional = true }
Expand Down
2 changes: 2 additions & 0 deletions src/util/semirings/mod.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
mod boolean;
mod expectation;
mod finitefield;
mod rational;
mod realsemiring;
mod semiring_traits;
mod tropical;

pub use self::boolean::*;
pub use self::expectation::*;
pub use self::finitefield::*;
pub use self::rational::*;
pub use self::realsemiring::*;
pub use self::semiring_traits::*;
pub use self::tropical::*;
39 changes: 39 additions & 0 deletions src/util/semirings/rational.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
use rational::Rational;
use std::{fmt::Display, ops};

use super::semiring_traits::Semiring;

#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub struct RationalSemiring(Rational);

impl Semiring for RationalSemiring {
fn one() -> Self {
RationalSemiring(Rational::new(1, 1))
}

fn zero() -> Self {
RationalSemiring(Rational::new(0, 1))
}
}

impl Display for RationalSemiring {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}/{}", self.0.numerator(), self.0.denominator())
}
}

impl ops::Add<RationalSemiring> for RationalSemiring {
type Output = RationalSemiring;

fn add(self, rhs: RationalSemiring) -> Self::Output {
RationalSemiring(self.0 + rhs.0)
}
}

impl ops::Mul<RationalSemiring> for RationalSemiring {
type Output = RationalSemiring;

fn mul(self, rhs: RationalSemiring) -> Self::Output {
RationalSemiring(self.0 * rhs.0)
}
}

0 comments on commit c3114ed

Please sign in to comment.