#![doc(include = "../../doc/references.md")]
use crate::numeric::*;
use crate::monoid::*;
use crate::helpers::*;
pub trait MulGroup: MulMonoid {
fn invert(&self) -> Self;
fn is_invertible(&self) -> bool;
fn div(&self, other: &Self) -> Self {
self.mul(&other.invert())
}
}
pub trait MulGroupLaws: MulGroup {
fn left_inverse(&self) -> bool {
self.invert().mul(self) == Self::one()
}
fn right_inverse(&self) -> bool {
self.mul(&self.invert()) == Self::one()
}
fn inverses(&self) -> bool {
self.left_inverse() && self.right_inverse()
}
}
impl<G: MulGroup> MulGroupLaws for G {}
pub trait NumMulGroupLaws: NumEq + MulGroup {
fn num_left_inverse(&self, eps: &Self::Eps) -> bool {
self.invert().mul(self).num_eq(&Self::one(), eps)
}
fn num_right_inverse(&self, eps: &Self::Eps) -> bool {
self.mul(&self.invert()).num_eq(&Self::one(), eps)
}
fn num_inverses(&self, eps: &Self::Eps) -> bool {
self.num_left_inverse(eps) && self.num_right_inverse(eps)
}
}
impl<G: NumEq + MulGroup> NumMulGroupLaws for G {}
macro_rules! float_mul_group {
($type:ty) => {
impl MulGroup for $type {
fn invert(&self) -> Self {
1.0 / *self
}
fn is_invertible(&self) -> bool {
*self != 0.0
}
}
};
($type:ty, $($others:ty),+) => {
float_mul_group! {$type}
float_mul_group! {$($others),+}
};
}
float_mul_group! {
f32, f64
}
impl MulGroup for () {
fn invert(&self) -> Self {}
fn is_invertible(&self) -> bool {
true
}
}
impl<A: MulGroup> MulGroup for (A,) {
fn invert(&self) -> Self {
(self.0.invert(), )
}
fn is_invertible(&self) -> bool {
self.0.is_invertible()
}
}
impl<A: MulGroup, B: MulGroup> MulGroup for (A, B) {
fn invert(&self) -> Self {
(self.0.invert(), self.1.invert())
}
fn is_invertible(&self) -> bool {
self.0.is_invertible() && self.1.is_invertible()
}
}
impl<A: MulGroup, B: MulGroup, C: MulGroup> MulGroup for (A, B, C) {
fn invert(&self) -> Self {
let (a, b, c) = self;
(a.invert(), b.invert(), c.invert())
}
fn is_invertible(&self) -> bool {
let (a, b, c) = self;
a.is_invertible() && b.is_invertible() && c.is_invertible()
}
}
macro_rules! array_mul_group {
($size:expr) => {
impl<T: Copy + MulGroup> MulGroup for [T; $size] {
fn is_invertible(&self) -> bool {
self.into_iter().all(|&x| x.is_invertible())
}
fn invert(&self) -> Self {
self.map(&|&x| x.invert())
}
}
};
($size:expr, $($others:expr),+) => {
array_mul_group! {$size}
array_mul_group! {$($others),+}
};
}
array_mul_group! {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16
}
#[cfg(test)]
mod tests;