fp_library/classes/
semigroup.rs

1/// A type class for types that support an associative binary operation.
2///
3/// `Semigroup` instances must satisfy the associative law:
4/// * Associativity: `append(a, append(b, c)) = append(append(a, b), c)`.
5pub trait Semigroup {
6	/// The result of combining the two values using the semigroup operation.
7	///
8	/// # Type Signature
9	///
10	/// `forall a. Semigroup a => (a, a) -> a`
11	///
12	/// # Parameters
13	///
14	/// * `a`: The first value.
15	/// * `b`: The second value.
16	///
17	/// # Returns
18	///
19	/// The combined value.
20	///
21	/// # Examples
22	///
23	/// ```
24	/// use fp_library::classes::semigroup::Semigroup;
25	/// use fp_library::types::string; // Import Semigroup impl for String
26	///
27	/// let x = "Hello, ".to_string();
28	/// let y = "World!".to_string();
29	/// let z = String::append(x, y);
30	/// assert_eq!(z, "Hello, World!".to_string());
31	/// ```
32	fn append(
33		a: Self,
34		b: Self,
35	) -> Self;
36}
37
38/// The result of combining the two values using the semigroup operation.
39///
40/// Free function version that dispatches to [the type class' associated function][`Semigroup::append`].
41///
42/// # Type Signature
43///
44/// `forall a. Semigroup a => (a, a) -> a`
45///
46/// # Parameters
47///
48/// * `a`: The first value.
49/// * `b`: The second value.
50///
51/// # Returns
52///
53/// The combined value.
54///
55/// # Examples
56///
57/// ```
58/// use fp_library::classes::semigroup::append;
59/// use fp_library::types::string; // Import Semigroup impl for String
60///
61/// let x = "Hello, ".to_string();
62/// let y = "World!".to_string();
63/// let z = append(x, y);
64/// assert_eq!(z, "Hello, World!".to_string());
65/// ```
66pub fn append<S: Semigroup>(
67	a: S,
68	b: S,
69) -> S {
70	S::append(a, b)
71}