Skip to main content

fp_library/classes/
monoid.rs

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