fp_library/classes/
monoid.rs

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