fp_library/classes/monoid.rs
1use super::semigroup::Semigroup;
2
3/// A type class for types that have an identity element and an associative binary operation.
4///
5/// `Monoid` extends [`Semigroup`] with an identity element.
6///
7/// # Laws
8///
9/// `Monoid` instances must satisfy the identity laws:
10/// * Left Identity: `append(empty(), a) = a`.
11/// * Right Identity: `append(a, empty()) = a`.
12pub trait Monoid: Semigroup {
13 /// The identity element.
14 ///
15 /// # Type Signature
16 ///
17 /// `forall a. Monoid a => () -> a`
18 ///
19 /// # Returns
20 ///
21 /// The identity element.
22 ///
23 /// # Examples
24 ///
25 /// ```
26 /// use fp_library::classes::monoid::Monoid;
27 /// use fp_library::types::string; // Import Monoid impl for String
28 ///
29 /// let x = String::empty();
30 /// assert_eq!(x, "".to_string());
31 /// ```
32 fn empty() -> Self;
33}
34
35/// The identity element.
36///
37/// Free function version that dispatches to [the type class' associated function][`Monoid::empty`].
38///
39/// # Type Signature
40///
41/// `forall a. Monoid a => () -> a`
42///
43/// # Returns
44///
45/// The identity element.
46///
47/// # Examples
48///
49/// ```
50/// use fp_library::classes::monoid::empty;
51/// use fp_library::types::string; // Import Monoid impl for String
52///
53/// let x: String = empty();
54/// assert_eq!(x, "".to_string());
55/// ```
56pub fn empty<M: Monoid>() -> M {
57 M::empty()
58}