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