Skip to main content

fp_library/classes/
foldable.rs

1//! Data structures that can be folded into a single value from the left or right.
2//!
3//! ### Examples
4//!
5//! ```
6//! use fp_library::{
7//! 	brands::*,
8//! 	functions::*,
9//! };
10//!
11//! let x = Some(5);
12//! let y = fold_right::<RcFnBrand, OptionBrand, _, _>(|a, b| a + b, 10, x);
13//! assert_eq!(y, 15);
14//! ```
15
16#[fp_macros::document_module]
17mod inner {
18	use {
19		crate::{
20			classes::*,
21			kinds::*,
22			types::*,
23		},
24		fp_macros::*,
25	};
26
27	/// A type class for structures that can be folded to a single value.
28	///
29	/// A `Foldable` represents a structure that can be folded over to combine its elements
30	/// into a single result.
31	///
32	/// ### Minimal Implementation
33	///
34	/// A minimal implementation of `Foldable` requires implementing either [`Foldable::fold_right`] or [`Foldable::fold_map`].
35	///
36	/// *   If [`Foldable::fold_right`] is implemented, [`Foldable::fold_map`] and [`Foldable::fold_left`] are derived from it.
37	/// *   If [`Foldable::fold_map`] is implemented, [`Foldable::fold_right`] is derived from it, and [`Foldable::fold_left`] is derived from the derived [`Foldable::fold_right`].
38	///
39	/// Note that [`Foldable::fold_left`] is not sufficient on its own because the default implementations of [`Foldable::fold_right`] and [`Foldable::fold_map`] do not depend on it.
40	pub trait Foldable: Kind_cdc7cd43dac7585f {
41		/// Folds the structure by applying a function from right to left.
42		///
43		/// This method performs a right-associative fold of the structure.
44		#[document_signature]
45		///
46		#[document_type_parameters(
47			"The lifetime of the elements.",
48			"The brand of the cloneable function to use.",
49			"The type of the elements in the structure.",
50			"The type of the accumulator."
51		)]
52		///
53		#[document_parameters(
54			"The function to apply to each element and the accumulator.",
55			"The initial value of the accumulator.",
56			"The structure to fold."
57		)]
58		///
59		#[document_returns("The final accumulator value.")]
60		#[document_examples]
61		///
62		/// ```
63		/// use fp_library::{
64		/// 	brands::*,
65		/// 	functions::*,
66		/// };
67		///
68		/// let x = Some(5);
69		/// let y = fold_right::<RcFnBrand, OptionBrand, _, _>(|a, b| a + b, 10, x);
70		/// assert_eq!(y, 15);
71		/// ```
72		fn fold_right<'a, FnBrand, A: 'a + Clone, B: 'a>(
73			func: impl Fn(A, B) -> B + 'a,
74			initial: B,
75			fa: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
76		) -> B
77		where
78			FnBrand: CloneableFn + 'a, {
79			let f = <FnBrand as CloneableFn>::new(move |(a, b)| func(a, b));
80			let m = Self::fold_map::<FnBrand, A, Endofunction<FnBrand, B>>(
81				move |a: A| {
82					let f = f.clone();
83					Endofunction::<FnBrand, B>::new(<FnBrand as CloneableFn>::new(move |b| {
84						f((a.clone(), b))
85					}))
86				},
87				fa,
88			);
89			m.0(initial)
90		}
91
92		/// Folds the structure by applying a function from left to right.
93		///
94		/// This method performs a left-associative fold of the structure.
95		#[document_signature]
96		///
97		#[document_type_parameters(
98			"The lifetime of the elements.",
99			"The brand of the cloneable function to use.",
100			"The type of the elements in the structure.",
101			"The type of the accumulator."
102		)]
103		///
104		#[document_parameters(
105			"The function to apply to the accumulator and each element.",
106			"The initial value of the accumulator.",
107			"The structure to fold."
108		)]
109		///
110		#[document_returns("The final accumulator value.")]
111		#[document_examples]
112		///
113		/// ```
114		/// use fp_library::{
115		/// 	brands::*,
116		/// 	functions::*,
117		/// };
118		///
119		/// let x = Some(5);
120		/// let y = fold_left::<RcFnBrand, OptionBrand, _, _>(|b, a| b + a, 10, x);
121		/// assert_eq!(y, 15);
122		/// ```
123		fn fold_left<'a, FnBrand, A: 'a + Clone, B: 'a>(
124			func: impl Fn(B, A) -> B + 'a,
125			initial: B,
126			fa: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
127		) -> B
128		where
129			FnBrand: CloneableFn + 'a, {
130			let f = <FnBrand as CloneableFn>::new(move |(b, a)| func(b, a));
131			let m = Self::fold_right::<FnBrand, A, Endofunction<FnBrand, B>>(
132				move |a: A, k: Endofunction<'a, FnBrand, B>| {
133					let f = f.clone();
134					// k is the "rest" of the computation.
135					// We want to perform "current" (f(b, a)) then "rest".
136					// Endofunction composition is f . g (f after g).
137					// So we want k . current.
138					// append(k, current).
139					let current =
140						Endofunction::<FnBrand, B>::new(<FnBrand as CloneableFn>::new(move |b| {
141							f((b, a.clone()))
142						}));
143					Semigroup::append(k, current)
144				},
145				Endofunction::<FnBrand, B>::empty(),
146				fa,
147			);
148			m.0(initial)
149		}
150
151		/// Maps values to a monoid and combines them.
152		///
153		/// This method maps each element of the structure to a monoid and then combines the results using the monoid's `append` operation.
154		#[document_signature]
155		///
156		#[document_type_parameters(
157			"The lifetime of the elements.",
158			"The brand of the cloneable function to use.",
159			"The type of the elements in the structure.",
160			"The type of the monoid."
161		)]
162		///
163		#[document_parameters(
164			"The function to map each element to a monoid.",
165			"The structure to fold."
166		)]
167		///
168		#[document_returns("The combined monoid value.")]
169		#[document_examples]
170		///
171		/// ```
172		/// use fp_library::{
173		/// 	brands::*,
174		/// 	functions::*,
175		/// };
176		///
177		/// let x = Some(5);
178		/// let y = fold_map::<RcFnBrand, OptionBrand, _, _>(|a: i32| a.to_string(), x);
179		/// assert_eq!(y, "5".to_string());
180		/// ```
181		fn fold_map<'a, FnBrand, A: 'a + Clone, M>(
182			func: impl Fn(A) -> M + 'a,
183			fa: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
184		) -> M
185		where
186			M: Monoid + 'a,
187			FnBrand: CloneableFn + 'a, {
188			Self::fold_right::<FnBrand, A, M>(move |a, m| M::append(func(a), m), M::empty(), fa)
189		}
190	}
191
192	/// Folds the structure by applying a function from right to left.
193	///
194	/// Free function version that dispatches to [the type class' associated function][`Foldable::fold_right`].
195	#[document_signature]
196	///
197	#[document_type_parameters(
198		"The lifetime of the elements.",
199		"The brand of the cloneable function to use.",
200		"The brand of the foldable structure.",
201		"The type of the elements in the structure.",
202		"The type of the accumulator."
203	)]
204	///
205	#[document_parameters(
206		"The function to apply to each element and the accumulator.",
207		"The initial value of the accumulator.",
208		"The structure to fold."
209	)]
210	///
211	#[document_returns("The final accumulator value.")]
212	#[document_examples]
213	///
214	/// ```
215	/// use fp_library::{
216	/// 	brands::*,
217	/// 	functions::*,
218	/// };
219	///
220	/// let x = Some(5);
221	/// let y = fold_right::<RcFnBrand, OptionBrand, _, _>(|a, b| a + b, 10, x);
222	/// assert_eq!(y, 15);
223	/// ```
224	pub fn fold_right<'a, FnBrand, Brand: Foldable, A: 'a + Clone, B: 'a>(
225		func: impl Fn(A, B) -> B + 'a,
226		initial: B,
227		fa: Apply!(<Brand as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
228	) -> B
229	where
230		FnBrand: CloneableFn + 'a, {
231		Brand::fold_right::<FnBrand, A, B>(func, initial, fa)
232	}
233
234	/// Folds the structure by applying a function from left to right.
235	///
236	/// Free function version that dispatches to [the type class' associated function][`Foldable::fold_left`].
237	#[document_signature]
238	///
239	#[document_type_parameters(
240		"The lifetime of the elements.",
241		"The brand of the cloneable function to use.",
242		"The brand of the foldable structure.",
243		"The type of the elements in the structure.",
244		"The type of the accumulator."
245	)]
246	///
247	#[document_parameters(
248		"The function to apply to the accumulator and each element.",
249		"The initial value of the accumulator.",
250		"The structure to fold."
251	)]
252	///
253	#[document_returns("The final accumulator value.")]
254	#[document_examples]
255	///
256	/// ```
257	/// use fp_library::{
258	/// 	brands::*,
259	/// 	functions::*,
260	/// };
261	///
262	/// let x = Some(5);
263	/// let y = fold_left::<RcFnBrand, OptionBrand, _, _>(|b, a| b + a, 10, x);
264	/// assert_eq!(y, 15);
265	/// ```
266	pub fn fold_left<'a, FnBrand, Brand: Foldable, A: 'a + Clone, B: 'a>(
267		func: impl Fn(B, A) -> B + 'a,
268		initial: B,
269		fa: Apply!(<Brand as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
270	) -> B
271	where
272		FnBrand: CloneableFn + 'a, {
273		Brand::fold_left::<FnBrand, A, B>(func, initial, fa)
274	}
275
276	/// Maps values to a monoid and combines them.
277	///
278	/// Free function version that dispatches to [the type class' associated function][`Foldable::fold_map`].
279	#[document_signature]
280	///
281	#[document_type_parameters(
282		"The lifetime of the elements.",
283		"The brand of the cloneable function to use.",
284		"The brand of the foldable structure.",
285		"The type of the elements in the structure.",
286		"The type of the monoid."
287	)]
288	///
289	#[document_parameters(
290		"The function to map each element to a monoid.",
291		"The structure to fold."
292	)]
293	///
294	#[document_returns("The combined monoid value.")]
295	#[document_examples]
296	///
297	/// ```
298	/// use fp_library::{
299	/// 	brands::*,
300	/// 	functions::*,
301	/// };
302	///
303	/// let x = Some(5);
304	/// let y = fold_map::<RcFnBrand, OptionBrand, _, _>(|a: i32| a.to_string(), x);
305	/// assert_eq!(y, "5".to_string());
306	/// ```
307	pub fn fold_map<'a, FnBrand, Brand: Foldable, A: 'a + Clone, M>(
308		func: impl Fn(A) -> M + 'a,
309		fa: Apply!(<Brand as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
310	) -> M
311	where
312		M: Monoid + 'a,
313		FnBrand: CloneableFn + 'a, {
314		Brand::fold_map::<FnBrand, A, M>(func, fa)
315	}
316}
317
318pub use inner::*;