From 45cf1fcdf3d0663d70a21a39b1c60422bfedcb8a Mon Sep 17 00:00:00 2001 From: Ben Ruijl Date: Sun, 28 Jul 2024 11:46:33 +0200 Subject: [PATCH] Add TryFrom for i64 and Rational - Add a method to get the coefficient ring from a polynomial ring --- src/coefficient.rs | 64 ++++++++++++++++++++++++++++++++++++++++++ src/poly/polynomial.rs | 5 ++++ 2 files changed, 69 insertions(+) diff --git a/src/coefficient.rs b/src/coefficient.rs index 2d21f8b4..35fc32b7 100644 --- a/src/coefficient.rs +++ b/src/coefficient.rs @@ -891,6 +891,70 @@ impl Add for CoefficientView<'_> { } } +impl TryFrom for i64 { + type Error = &'static str; + + fn try_from(value: Atom) -> Result { + value.as_view().try_into() + } +} + +impl TryFrom<&Atom> for i64 { + type Error = &'static str; + + fn try_from(value: &Atom) -> Result { + value.as_view().try_into() + } +} + +impl<'a> TryFrom> for i64 { + type Error = &'static str; + + fn try_from(value: AtomView<'a>) -> Result { + if let AtomView::Num(n) = value { + if let CoefficientView::Natural(n, 1) = n.get_coeff_view() { + return Ok(n); + } else { + Err("Not an i64") + } + } else { + Err("Not a number") + } + } +} + +impl TryFrom for Rational { + type Error = &'static str; + + fn try_from(value: Atom) -> Result { + value.as_view().try_into() + } +} + +impl TryFrom<&Atom> for Rational { + type Error = &'static str; + + fn try_from(value: &Atom) -> Result { + value.as_view().try_into() + } +} + +impl<'a> TryFrom> for Rational { + type Error = &'static str; + + fn try_from(value: AtomView<'a>) -> Result { + if let AtomView::Num(n) = value { + match n.get_coeff_view() { + CoefficientView::Natural(n, d) => Ok(Rational::from_unchecked(n, d)), + CoefficientView::Large(r) => Ok(r.to_rat()), + _ => Err("Not a rational"), + } + } else { + Err("Not a number") + } + } +} + impl Atom { /// Set the coefficient ring to the multivariate rational polynomial with `vars` variables. pub fn set_coefficient_ring(&self, vars: &Arc>) -> Atom { diff --git a/src/poly/polynomial.rs b/src/poly/polynomial.rs index d2416bd5..c2e4bcd2 100755 --- a/src/poly/polynomial.rs +++ b/src/poly/polynomial.rs @@ -45,6 +45,11 @@ impl PolynomialRing { _phantom_exp: PhantomData, } } + + /// Get the coefficient ring. + pub fn coefficient_ring(&self) -> &R { + &self.ring + } } impl std::fmt::Display for PolynomialRing {