un_algebra 0.9.0

Simple implementations of selected abstract algebraic structures--including groups, rings, and fields. Intended for self-study of abstract algebra concepts and not for production use.
//!
//! Commutative rings.
//!
//! An algebraic _commutative_ _ring_ `R`, is a _ring_ (formally a
//! _ring_ _with_ _identity_) where the _multiplication_ operation `×`
//! is _commutative_.
//!
//! # Axioms
//!
//! ```text
//! ∀g, h ∈ R
//!
//! Commutivity: g × h = h × g.
//! ```
//!
//! # References
//!
//! See [references] for a formal definition of a commutative ring.
//!
#![doc(include = "../../doc/references.md")]

use crate::ring::*;
use crate::numeric::*;


///
/// An algebraic _commutative ring_.
///
pub trait ComRing: Ring {}


///
/// Laws of commutative rings.
///
pub trait ComRingLaws: ComRing {

  /// The axiom of _multiplicative_ _commutivity_.
  fn commutivity(&self, x: &Self) -> bool {
    self.mul(x) == x.mul(self)
  }
}


///
/// Blanket implementation of commutative ring laws for commutative ring
/// implementations.
///
impl<R: ComRing> ComRingLaws for R {}


///
/// Numeric laws of commutative rings.
///
pub trait NumComRingLaws: NumEq + ComRing {

  /// The numeric axiom of _multiplicative_ _commutivity_.
  fn num_commutivity(&self, x: &Self, eps: &Self::Eps) -> bool {
    self.mul(x).num_eq(&x.mul(self), eps)
  }
}


///
/// Blanket implementation of numeric commutative ring laws for
/// commutative ring implementations.
///
impl<R: NumEq + ComRing> NumComRingLaws for R {}


///
/// Define `ComRing` implementations for numeric types.
///
macro_rules! numeric_com_ring {
  ($type:ty) => {
    impl ComRing for $type {}
  };

  ($type:ty, $($others:ty),+) => {
    numeric_com_ring! {$type}
    numeric_com_ring! {$($others),+}
  };
}


// Only signed integer and float types form a commutative ring.
numeric_com_ring! {
  i8, i16, i32, i64, i128, isize, f32, f64
}


///
/// 0-tuples form a commutative ring.
///
impl ComRing for () {}


///
/// 1-tuples form a commutative ring when their items do.
///
impl<A: ComRing> ComRing for (A,) {}


///
/// 2-tuples form a commutative ring when their items do.
///
impl<A: ComRing, B: ComRing> ComRing for (A, B) {}


///
/// 3-tuples form a commutative ring when their items do.
///
impl<A: ComRing, B: ComRing, C: ComRing> ComRing for (A, B, C) {}


///
/// Define `ComRing` implementations for arrays. Maybe not needed if
/// Rust had _const_ _generics_.
///
macro_rules! array_com_ring {
  ($size:expr) => {
    impl<T: Copy + ComRing> ComRing for [T; $size] {}
  };

  ($size:expr, $($others:expr),+) => {
    array_com_ring! {$size}
    array_com_ring! {$($others),+}
  };
}


// Array commutative ring types.
array_com_ring! {
  0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16
}


// Module unit tests are in a sub-module.
#[cfg(test)]
mod tests;