fp_library/typeclasses/monoid.rs
1use crate::typeclasses::Semigroup;
2
3/// A typeclass for monoids.
4///
5/// `Monoid` extends [`Semigroup`] with an identity element. A monoid is a set
6/// equipped with an associative binary operation and an identity element.
7///
8/// In functional programming, monoids are useful for combining values in
9/// a consistent way, especially when accumulating results or folding
10/// collections.
11///
12/// # Laws
13///
14/// Monoid instances must satisfy the following laws:
15/// * Left identity: `append(empty(), x) = x`.
16/// * Right identity: `append(x, empty()) = x`.
17/// * Associativity: `append(append(x, y), z) = append(x, append(y, z))`.
18///
19/// # Examples
20///
21/// Common monoids include:
22/// * Strings with concatenation and empty string.
23/// * Numbers with addition and zero.
24/// * Numbers with multiplication and one.
25/// * Lists with concatenation and empty list.
26pub trait Monoid: Semigroup {
27 /// Returns the identity element for the monoid.
28 ///
29 /// # Type Signature
30 ///
31 /// `forall a. Monoid a => () -> a`
32 ///
33 /// # Returns
34 ///
35 /// The identity element which, when combined with any other element
36 /// using the semigroup operation, leaves the other element unchanged.
37 fn empty() -> Self;
38}
39
40/// Returns the identity element for the monoid.
41///
42/// Free function version that dispatches to [the typeclass' associated function][`Monoid::empty`].
43///
44/// # Type Signature
45///
46/// `forall a. Monoid a => () -> a`
47///
48/// # Returns
49///
50/// The identity element which, when combined with any other element
51/// using the semigroup operation, leaves the other element unchanged.
52///
53/// # Examples
54///
55/// ```
56/// use fp_library::functions::empty;
57///
58/// assert_eq!(empty::<String>(), "".to_string());
59/// ```
60pub fn empty<Brand: Monoid>() -> Brand {
61 Brand::empty()
62}