Skip to main content

fp_library/types/
string.rs

1use crate::{
2	classes::{monoid::Monoid, semigroup::Semigroup},
3	impl_kind,
4	kinds::*,
5};
6
7impl_kind! {
8	for String {
9		type Of<'a> = String;
10	}
11}
12
13impl Semigroup for String {
14	/// The result of combining two strings.
15	///
16	/// This method combines two strings into a single string.
17	///
18	/// ### Type Signature
19	///
20	/// `Semigroup String => (String, String) -> String`
21	///
22	/// ### Parameters
23	///
24	/// * `a`: The first string.
25	/// * `b`: The second string.
26	///
27	/// ### Returns
28	///
29	/// The combined string.
30	///
31	/// ### Examples
32	///
33	/// ```
34	/// use fp_library::functions::*;
35	///
36	/// let s1 = "Hello, ".to_string();
37	/// let s2 = "World!".to_string();
38	/// let result = append::<_>(s1, s2);
39	/// assert_eq!(result, "Hello, World!");
40	/// ```
41	fn append(
42		a: Self,
43		b: Self,
44	) -> Self {
45		a + &b
46	}
47}
48
49impl Monoid for String {
50	/// The identity element.
51	///
52	/// This method returns the identity element of the monoid.
53	///
54	/// ### Type Signature
55	///
56	/// `Monoid String => () -> String`
57	///
58	/// ### Returns
59	///
60	/// The identity element.
61	///
62	/// ### Examples
63	///
64	/// ```
65	/// use fp_library::functions::*;
66	///
67	/// let empty_string = empty::<String>();
68	/// assert_eq!(empty_string, "");
69	/// ```
70	fn empty() -> Self {
71		String::new()
72	}
73}
74
75#[cfg(test)]
76mod tests {
77	use crate::classes::{monoid::Monoid, semigroup::append};
78	use quickcheck_macros::quickcheck;
79
80	// Semigroup Laws
81
82	/// Tests the associativity law for Semigroup.
83	#[quickcheck]
84	fn semigroup_associativity(
85		a: String,
86		b: String,
87		c: String,
88	) -> bool {
89		append(a.clone(), append(b.clone(), c.clone())) == append(append(a, b), c)
90	}
91
92	// Monoid Laws
93
94	/// Tests the left identity law for Monoid.
95	#[quickcheck]
96	fn monoid_left_identity(a: String) -> bool {
97		append(String::empty(), a.clone()) == a
98	}
99
100	/// Tests the right identity law for Monoid.
101	#[quickcheck]
102	fn monoid_right_identity(a: String) -> bool {
103		append(a.clone(), String::empty()) == a
104	}
105}