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