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