Skip to main content

fp_library/classes/
send_ref_foldable.rs

1//! Thread-safe by-reference variant of [`Foldable`](crate::classes::Foldable).
2//!
3//! **User story:** "I want to fold over a thread-safe memoized value by reference."
4//!
5//! ### Examples
6//!
7//! ```
8//! use fp_library::{
9//! 	brands::*,
10//! 	classes::send_ref_foldable::*,
11//! 	types::*,
12//! };
13//!
14//! let lazy = ArcLazy::new(|| 10);
15//! let result = send_ref_fold_map::<ArcFnBrand, LazyBrand<ArcLazyConfig>, _, _>(
16//! 	|a: &i32| a.to_string(),
17//! 	&lazy,
18//! );
19//! assert_eq!(result, "10");
20//! ```
21
22#[fp_macros::document_module]
23mod inner {
24	use {
25		crate::{
26			classes::{
27				send_clone_fn::SendLiftFn,
28				*,
29			},
30			kinds::*,
31			types::{
32				Dual,
33				SendEndofunction,
34			},
35		},
36		fp_macros::*,
37	};
38
39	/// Thread-safe by-reference folding over a structure.
40	///
41	/// Similar to [`RefFoldable`], but closures and elements must be `Send + Sync`.
42	/// Unlike [`ParRefFunctor`](crate::classes::ParRefFunctor) (which requires
43	/// [`RefFunctor`](crate::classes::RefFunctor) as a supertrait), `SendRefFoldable`
44	/// does not require `RefFoldable`. This is because the SendRef monadic traits
45	/// (functor, pointed, lift, applicative) construct new containers internally,
46	/// and `ArcLazy::new` requires `Send` on closures, which `Ref` trait signatures
47	/// do not guarantee. The SendRef and Ref hierarchies are therefore independent.
48	///
49	/// All three methods (`send_ref_fold_map`, `send_ref_fold_right`, `send_ref_fold_left`)
50	/// have default implementations in terms of each other, so implementors
51	/// only need to provide one.
52	#[kind(type Of<'a, A: 'a>: 'a;)]
53	pub trait SendRefFoldable {
54		/// Maps values to a monoid by reference and combines them (thread-safe).
55		#[document_signature]
56		#[document_type_parameters(
57			"The lifetime of the elements.",
58			"The brand of the cloneable function to use.",
59			"The type of the elements.",
60			"The monoid type."
61		)]
62		#[document_parameters(
63			"The function to map each element reference to a monoid. Must be `Send + Sync`.",
64			"The structure to fold."
65		)]
66		#[document_returns("The combined monoid value.")]
67		#[document_examples]
68		///
69		/// ```
70		/// use fp_library::{
71		/// 	brands::*,
72		/// 	classes::send_ref_foldable::*,
73		/// 	types::*,
74		/// };
75		///
76		/// let lazy = ArcLazy::new(|| 5);
77		/// let result = send_ref_fold_map::<ArcFnBrand, LazyBrand<ArcLazyConfig>, _, _>(
78		/// 	|a: &i32| a.to_string(),
79		/// 	&lazy,
80		/// );
81		/// assert_eq!(result, "5");
82		/// ```
83		fn send_ref_fold_map<'a, FnBrand, A: Send + Sync + 'a + Clone, M>(
84			func: impl Fn(&A) -> M + Send + Sync + 'a,
85			fa: &Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
86		) -> M
87		where
88			FnBrand: SendLiftFn + 'a,
89			M: Monoid + Send + Sync + 'a, {
90			Self::send_ref_fold_right::<FnBrand, A, M>(
91				move |a: &A, acc| Semigroup::append(func(a), acc),
92				Monoid::empty(),
93				fa,
94			)
95		}
96
97		/// Folds the structure from the right by reference (thread-safe).
98		#[document_signature]
99		#[document_type_parameters(
100			"The lifetime of the elements.",
101			"The brand of the cloneable function to use.",
102			"The type of the elements.",
103			"The type of the accumulator."
104		)]
105		#[document_parameters(
106			"The function to apply to each element reference and accumulator. Must be `Send + Sync`.",
107			"The initial value of the accumulator.",
108			"The structure to fold."
109		)]
110		#[document_returns("The final accumulator value.")]
111		#[document_examples]
112		///
113		/// ```
114		/// use fp_library::{
115		/// 	brands::*,
116		/// 	classes::send_ref_foldable::SendRefFoldable,
117		/// 	types::*,
118		/// };
119		///
120		/// let lazy = ArcLazy::new(|| 10);
121		/// let result = <LazyBrand<ArcLazyConfig> as SendRefFoldable>::send_ref_fold_right::<
122		/// 	ArcFnBrand,
123		/// 	_,
124		/// 	_,
125		/// >(|a: &i32, acc: i32| acc + *a, 0, &lazy);
126		/// assert_eq!(result, 10);
127		/// ```
128		fn send_ref_fold_right<'a, FnBrand, A: Send + Sync + 'a + Clone, B: Send + Sync + 'a>(
129			func: impl Fn(&A, B) -> B + Send + Sync + 'a,
130			initial: B,
131			fa: &Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
132		) -> B
133		where
134			FnBrand: SendLiftFn + 'a, {
135			let f = <FnBrand as SendLiftFn>::new(move |(a, b): (A, B)| func(&a, b));
136			let m = Self::send_ref_fold_map::<FnBrand, A, SendEndofunction<FnBrand, B>>(
137				move |a: &A| {
138					let a = a.clone();
139					let f = f.clone();
140					SendEndofunction::<FnBrand, B>::new(<FnBrand as SendLiftFn>::new(move |b| {
141						let a = a.clone();
142						f((a, b))
143					}))
144				},
145				fa,
146			);
147			m.0(initial)
148		}
149
150		/// Folds the structure from the left by reference (thread-safe).
151		#[document_signature]
152		#[document_type_parameters(
153			"The lifetime of the elements.",
154			"The brand of the cloneable function to use.",
155			"The type of the elements.",
156			"The type of the accumulator."
157		)]
158		#[document_parameters(
159			"The function to apply to the accumulator and each element reference. Must be `Send + Sync`.",
160			"The initial value of the accumulator.",
161			"The structure to fold."
162		)]
163		#[document_returns("The final accumulator value.")]
164		#[document_examples]
165		///
166		/// ```
167		/// use fp_library::{
168		/// 	brands::*,
169		/// 	classes::send_ref_foldable::SendRefFoldable,
170		/// 	types::*,
171		/// };
172		///
173		/// let lazy = ArcLazy::new(|| 10);
174		/// let result = <LazyBrand<ArcLazyConfig> as SendRefFoldable>::send_ref_fold_left::<
175		/// 	ArcFnBrand,
176		/// 	_,
177		/// 	_,
178		/// >(|acc: i32, a: &i32| acc + *a, 0, &lazy);
179		/// assert_eq!(result, 10);
180		/// ```
181		fn send_ref_fold_left<'a, FnBrand, A: Send + Sync + 'a + Clone, B: Send + Sync + 'a>(
182			func: impl Fn(B, &A) -> B + Send + Sync + 'a,
183			initial: B,
184			fa: &Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
185		) -> B
186		where
187			FnBrand: SendLiftFn + 'a, {
188			let f = <FnBrand as SendLiftFn>::new(move |(b, a): (B, A)| func(b, &a));
189			let m = Self::send_ref_fold_map::<FnBrand, A, Dual<SendEndofunction<FnBrand, B>>>(
190				move |a: &A| {
191					let a = a.clone();
192					let f = f.clone();
193					Dual(SendEndofunction::<FnBrand, B>::new(<FnBrand as SendLiftFn>::new(
194						move |b| {
195							let a = a.clone();
196							f((b, a))
197						},
198					)))
199				},
200				fa,
201			);
202			(m.0).0(initial)
203		}
204	}
205
206	/// Maps values to a monoid by reference and combines them (thread-safe).
207	///
208	/// Free function version that dispatches to [the type class' associated function][`SendRefFoldable::send_ref_fold_map`].
209	#[document_signature]
210	#[document_type_parameters(
211		"The lifetime of the elements.",
212		"The brand of the cloneable function to use.",
213		"The brand of the structure.",
214		"The type of the elements.",
215		"The monoid type."
216	)]
217	#[document_parameters(
218		"The function to map each element reference to a monoid.",
219		"The structure to fold."
220	)]
221	#[document_returns("The combined monoid value.")]
222	#[document_examples]
223	///
224	/// ```
225	/// use fp_library::{
226	/// 	brands::*,
227	/// 	classes::send_ref_foldable::*,
228	/// 	types::*,
229	/// };
230	///
231	/// let lazy = ArcLazy::new(|| 5);
232	/// let result = send_ref_fold_map::<ArcFnBrand, LazyBrand<ArcLazyConfig>, _, _>(
233	/// 	|a: &i32| a.to_string(),
234	/// 	&lazy,
235	/// );
236	/// assert_eq!(result, "5");
237	/// ```
238	pub fn send_ref_fold_map<
239		'a,
240		FnBrand: SendLiftFn + 'a,
241		Brand: SendRefFoldable,
242		A: Send + Sync + 'a + Clone,
243		M,
244	>(
245		func: impl Fn(&A) -> M + Send + Sync + 'a,
246		fa: &Apply!(<Brand as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
247	) -> M
248	where
249		M: Monoid + Send + Sync + 'a, {
250		Brand::send_ref_fold_map::<FnBrand, A, M>(func, fa)
251	}
252}
253
254pub use inner::*;