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