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	///
41	/// ### Laws
42	///
43	/// `Foldable` instances must be internally consistent:
44	/// * fold_map/fold_right consistency: `fold_map(f, fa) = fold_right(|a, m| append(f(a), m), empty(), fa)`.
45	#[document_examples]
46	///
47	/// Foldable laws for [`Vec`]:
48	///
49	/// ```
50	/// use fp_library::{
51	/// 	brands::*,
52	/// 	functions::*,
53	/// };
54	///
55	/// let xs = vec![1, 2, 3];
56	/// let f = |a: i32| a.to_string();
57	///
58	/// // fold_map/fold_right consistency:
59	/// // fold_map(f, fa) = fold_right(|a, m| append(f(a), m), empty(), fa)
60	/// assert_eq!(
61	/// 	fold_map::<RcFnBrand, VecBrand, _, _>(f, xs.clone()),
62	/// 	fold_right::<RcFnBrand, VecBrand, _, _>(
63	/// 		|a: i32, m: String| append(f(a), m),
64	/// 		empty::<String>(),
65	/// 		xs,
66	/// 	),
67	/// );
68	/// ```
69	pub trait Foldable: Kind_cdc7cd43dac7585f {
70		/// Folds the structure by applying a function from right to left.
71		///
72		/// This method performs a right-associative fold of the structure.
73		#[document_signature]
74		///
75		#[document_type_parameters(
76			"The lifetime of the elements.",
77			"The brand of the cloneable function to use.",
78			"The type of the elements in the structure.",
79			"The type of the accumulator."
80		)]
81		///
82		#[document_parameters(
83			"The function to apply to each element and the accumulator.",
84			"The initial value of the accumulator.",
85			"The structure to fold."
86		)]
87		///
88		#[document_returns("The final accumulator value.")]
89		#[document_examples]
90		///
91		/// ```
92		/// use fp_library::{
93		/// 	brands::*,
94		/// 	functions::*,
95		/// };
96		///
97		/// let x = Some(5);
98		/// let y = fold_right::<RcFnBrand, OptionBrand, _, _>(|a, b| a + b, 10, x);
99		/// assert_eq!(y, 15);
100		/// ```
101		fn fold_right<'a, FnBrand, A: 'a + Clone, B: 'a>(
102			func: impl Fn(A, B) -> B + 'a,
103			initial: B,
104			fa: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
105		) -> B
106		where
107			FnBrand: CloneableFn + 'a, {
108			let f = <FnBrand as CloneableFn>::new(move |(a, b)| func(a, b));
109			let m = Self::fold_map::<FnBrand, A, Endofunction<FnBrand, B>>(
110				move |a: A| {
111					let f = f.clone();
112					Endofunction::<FnBrand, B>::new(<FnBrand as CloneableFn>::new(move |b| {
113						f((a.clone(), b))
114					}))
115				},
116				fa,
117			);
118			m.0(initial)
119		}
120
121		/// Folds the structure by applying a function from left to right.
122		///
123		/// This method performs a left-associative fold of the structure.
124		#[document_signature]
125		///
126		#[document_type_parameters(
127			"The lifetime of the elements.",
128			"The brand of the cloneable function to use.",
129			"The type of the elements in the structure.",
130			"The type of the accumulator."
131		)]
132		///
133		#[document_parameters(
134			"The function to apply to the accumulator and each element.",
135			"The initial value of the accumulator.",
136			"The structure to fold."
137		)]
138		///
139		#[document_returns("The final accumulator value.")]
140		#[document_examples]
141		///
142		/// ```
143		/// use fp_library::{
144		/// 	brands::*,
145		/// 	functions::*,
146		/// };
147		///
148		/// let x = Some(5);
149		/// let y = fold_left::<RcFnBrand, OptionBrand, _, _>(|b, a| b + a, 10, x);
150		/// assert_eq!(y, 15);
151		/// ```
152		fn fold_left<'a, FnBrand, A: 'a + Clone, B: 'a>(
153			func: impl Fn(B, A) -> B + 'a,
154			initial: B,
155			fa: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
156		) -> B
157		where
158			FnBrand: CloneableFn + 'a, {
159			let f = <FnBrand as CloneableFn>::new(move |(b, a)| func(b, a));
160			let m = Self::fold_right::<FnBrand, A, Endofunction<FnBrand, B>>(
161				move |a: A, k: Endofunction<'a, FnBrand, B>| {
162					let f = f.clone();
163					// k is the "rest" of the computation.
164					// We want to perform "current" (f(b, a)) then "rest".
165					// Endofunction composition is f . g (f after g).
166					// So we want k . current.
167					// append(k, current).
168					let current =
169						Endofunction::<FnBrand, B>::new(<FnBrand as CloneableFn>::new(move |b| {
170							f((b, a.clone()))
171						}));
172					Semigroup::append(k, current)
173				},
174				Endofunction::<FnBrand, B>::empty(),
175				fa,
176			);
177			m.0(initial)
178		}
179
180		/// Maps values to a monoid and combines them.
181		///
182		/// This method maps each element of the structure to a monoid and then combines the results using the monoid's `append` operation.
183		#[document_signature]
184		///
185		#[document_type_parameters(
186			"The lifetime of the elements.",
187			"The brand of the cloneable function to use.",
188			"The type of the elements in the structure.",
189			"The type of the monoid."
190		)]
191		///
192		#[document_parameters(
193			"The function to map each element to a monoid.",
194			"The structure to fold."
195		)]
196		///
197		#[document_returns("The combined monoid value.")]
198		#[document_examples]
199		///
200		/// ```
201		/// use fp_library::{
202		/// 	brands::*,
203		/// 	functions::*,
204		/// };
205		///
206		/// let x = Some(5);
207		/// let y = fold_map::<RcFnBrand, OptionBrand, _, _>(|a: i32| a.to_string(), x);
208		/// assert_eq!(y, "5".to_string());
209		/// ```
210		fn fold_map<'a, FnBrand, A: 'a + Clone, M>(
211			func: impl Fn(A) -> M + 'a,
212			fa: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
213		) -> M
214		where
215			M: Monoid + 'a,
216			FnBrand: CloneableFn + 'a, {
217			Self::fold_right::<FnBrand, A, M>(move |a, m| M::append(func(a), m), M::empty(), fa)
218		}
219	}
220
221	/// Folds the structure by applying a function from right to left.
222	///
223	/// Free function version that dispatches to [the type class' associated function][`Foldable::fold_right`].
224	#[document_signature]
225	///
226	#[document_type_parameters(
227		"The lifetime of the elements.",
228		"The brand of the cloneable function to use.",
229		"The brand of the foldable structure.",
230		"The type of the elements in the structure.",
231		"The type of the accumulator."
232	)]
233	///
234	#[document_parameters(
235		"The function to apply to each element and the accumulator.",
236		"The initial value of the accumulator.",
237		"The structure to fold."
238	)]
239	///
240	#[document_returns("The final accumulator value.")]
241	#[document_examples]
242	///
243	/// ```
244	/// use fp_library::{
245	/// 	brands::*,
246	/// 	functions::*,
247	/// };
248	///
249	/// let x = Some(5);
250	/// let y = fold_right::<RcFnBrand, OptionBrand, _, _>(|a, b| a + b, 10, x);
251	/// assert_eq!(y, 15);
252	/// ```
253	pub fn fold_right<'a, FnBrand, Brand: Foldable, A: 'a + Clone, B: 'a>(
254		func: impl Fn(A, B) -> B + 'a,
255		initial: B,
256		fa: Apply!(<Brand as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
257	) -> B
258	where
259		FnBrand: CloneableFn + 'a, {
260		Brand::fold_right::<FnBrand, A, B>(func, initial, fa)
261	}
262
263	/// Folds the structure by applying a function from left to right.
264	///
265	/// Free function version that dispatches to [the type class' associated function][`Foldable::fold_left`].
266	#[document_signature]
267	///
268	#[document_type_parameters(
269		"The lifetime of the elements.",
270		"The brand of the cloneable function to use.",
271		"The brand of the foldable structure.",
272		"The type of the elements in the structure.",
273		"The type of the accumulator."
274	)]
275	///
276	#[document_parameters(
277		"The function to apply to the accumulator and each element.",
278		"The initial value of the accumulator.",
279		"The structure to fold."
280	)]
281	///
282	#[document_returns("The final accumulator value.")]
283	#[document_examples]
284	///
285	/// ```
286	/// use fp_library::{
287	/// 	brands::*,
288	/// 	functions::*,
289	/// };
290	///
291	/// let x = Some(5);
292	/// let y = fold_left::<RcFnBrand, OptionBrand, _, _>(|b, a| b + a, 10, x);
293	/// assert_eq!(y, 15);
294	/// ```
295	pub fn fold_left<'a, FnBrand, Brand: Foldable, A: 'a + Clone, B: 'a>(
296		func: impl Fn(B, A) -> B + 'a,
297		initial: B,
298		fa: Apply!(<Brand as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
299	) -> B
300	where
301		FnBrand: CloneableFn + 'a, {
302		Brand::fold_left::<FnBrand, A, B>(func, initial, fa)
303	}
304
305	/// Maps values to a monoid and combines them.
306	///
307	/// Free function version that dispatches to [the type class' associated function][`Foldable::fold_map`].
308	#[document_signature]
309	///
310	#[document_type_parameters(
311		"The lifetime of the elements.",
312		"The brand of the cloneable function to use.",
313		"The brand of the foldable structure.",
314		"The type of the elements in the structure.",
315		"The type of the monoid."
316	)]
317	///
318	#[document_parameters(
319		"The function to map each element to a monoid.",
320		"The structure to fold."
321	)]
322	///
323	#[document_returns("The combined monoid value.")]
324	#[document_examples]
325	///
326	/// ```
327	/// use fp_library::{
328	/// 	brands::*,
329	/// 	functions::*,
330	/// };
331	///
332	/// let x = Some(5);
333	/// let y = fold_map::<RcFnBrand, OptionBrand, _, _>(|a: i32| a.to_string(), x);
334	/// assert_eq!(y, "5".to_string());
335	/// ```
336	pub fn fold_map<'a, FnBrand, Brand: Foldable, A: 'a + Clone, M>(
337		func: impl Fn(A) -> M + 'a,
338		fa: Apply!(<Brand as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
339	) -> M
340	where
341		M: Monoid + 'a,
342		FnBrand: CloneableFn + 'a, {
343		Brand::fold_map::<FnBrand, A, M>(func, fa)
344	}
345}
346
347pub use inner::*;