deep_causality_num/algebra/
module.rs

1/*
2 * SPDX-License-Identifier: MIT
3 * Copyright (c) "2025" . The DeepCausality Authors and Contributors. All Rights Reserved.
4 */
5use crate::{AbelianGroup, Ring};
6use core::ops::{Mul, MulAssign};
7
8/// Represents a **Module** over a `Ring`.
9///
10/// A module is a generalization of a vector space, where the scalars are
11/// elements of a `Ring` `R` rather than being restricted to a `Field`.
12///
13/// # Mathematical Definition
14///
15/// A left module `M` over a ring `R` consists of an abelian group `(M, +)` and
16/// an operation `R × M → M` (scalar multiplication) such that for all
17/// `r, s` in `R` and `x, y` in `M`, the following axioms hold:
18///
19/// 1.  `r * (x + y) = r*x + r*y`
20/// 2.  `(r + s) * x = r*x + s*x`
21/// 3.  `(r * s) * x = r * (s * x)`
22/// 4.  `1 * x = x` (if `R` is a unital ring)
23///
24/// ## Structure in this Crate
25/// -   The "vectors" (`Self`) form an `AbelianGroup`.
26/// -   The "scalars" (`R`) form a `Ring`.
27/// -   Scalar multiplication is provided by implementing `Mul<R>` and `MulAssign<R>`.
28///
29/// ## Examples
30/// -   Any `AbelianGroup` `G` is a module over the ring of integers `Z`.
31/// -   A vector space is a module where the ring of scalars is a `Field`.
32/// -   `Complex<T>` is a module over the `RealField` `T`.
33pub trait Module<R: Ring>: AbelianGroup + Mul<R, Output = Self> + MulAssign<R> {
34    /// Scales the module element by a scalar from the ring `R`.
35    ///
36    /// This is a convenience method that clones `self` and applies the `*`
37    /// operator for scalar multiplication.
38    ///
39    /// # Arguments
40    /// * `scalar`: The scalar value of type `R` to multiply by.
41    ///
42    /// # Returns
43    /// A new element of `Self` representing the scaled result.
44    fn scale(&self, scalar: R) -> Self {
45        // We must clone because `Mul` usually consumes `self` (value semantics),
46        // but `scale` takes `&self` (reference semantics).
47        // We know Self is Clone because AbelianGroup -> AddGroup -> Clone.
48        self.clone() * scalar
49    }
50
51    /// Scales the module element in-place by a scalar from the ring `R`.
52    ///
53    /// This is a convenience method that uses the `MulAssign` (`*=`) operator
54    /// for in-place scalar multiplication. This is often more efficient for
55    /// large data structures like tensors as it avoids allocation.
56    ///
57    /// # Arguments
58    /// * `scalar`: The scalar value of type `R` to multiply by.
59    fn scale_mut(&mut self, scalar: R) {
60        *self *= scalar; // Uses MulAssign
61    }
62}
63
64// Blanket implementation for any type that satisfies the bounds
65impl<V, R> Module<R> for V
66where
67    V: AbelianGroup + Mul<R, Output = V> + MulAssign<R>,
68    R: Ring,
69{
70}