Skip to main content

fp_library/classes/
ref_bifunctor.rs

1//! Types that can be mapped over two type arguments simultaneously by reference.
2//!
3//! ### Examples
4//!
5//! ```
6//! use fp_library::{
7//! 	brands::*,
8//! 	functions::explicit::*,
9//! };
10//!
11//! let x = Result::<i32, i32>::Ok(5);
12//! let y = bimap::<ResultBrand, _, _, _, _, _, _>((|e: &i32| *e + 1, |s: &i32| *s * 2), &x);
13//! assert_eq!(y, Ok(10));
14//! ```
15
16#[fp_macros::document_module]
17mod inner {
18	use {
19		crate::{
20			brands::*,
21			classes::*,
22			kinds::*,
23		},
24		fp_macros::*,
25	};
26
27	/// A type class for types that can be mapped over two type arguments by reference.
28	///
29	/// This is the by-reference variant of [`Bifunctor`]. Both closures receive references
30	/// to the values (`&A` and `&C`) and produce owned output (`B` and `D`). The container
31	/// is borrowed, not consumed.
32	///
33	/// Unlike [`RefFunctor`] for partially-applied bifunctor brands (e.g.,
34	/// `ResultErrAppliedBrand<E>`), `RefBifunctor` does not require `Clone` on either
35	/// type parameter because both sides have closures to handle their respective types.
36	///
37	/// ### Laws
38	///
39	/// `RefBifunctor` instances must satisfy the following laws:
40	///
41	/// **Identity:** `ref_bimap(|x| x.clone(), |x| x.clone(), &p)` is equivalent to
42	/// `p.clone()`, given `A: Clone, C: Clone`.
43	///
44	/// **Composition:** `ref_bimap(|x| f2(&f1(x)), |x| g2(&g1(x)), &p)` is equivalent to
45	/// `ref_bimap(f2, g2, &ref_bimap(f1, g1, &p))`.
46	#[document_examples]
47	///
48	/// RefBifunctor laws for [`Result`]:
49	///
50	/// ```
51	/// use fp_library::{
52	/// 	brands::*,
53	/// 	functions::{
54	/// 		explicit::bimap,
55	/// 		*,
56	/// 	},
57	/// };
58	///
59	/// let ok: Result<i32, i32> = Ok(5);
60	/// let err: Result<i32, i32> = Err(3);
61	///
62	/// // Identity: ref_bimap(Clone::clone, Clone::clone, &p) == p.clone()
63	/// assert_eq!(bimap::<ResultBrand, _, _, _, _, _, _>((|x: &i32| *x, |x: &i32| *x), &ok), ok,);
64	/// assert_eq!(bimap::<ResultBrand, _, _, _, _, _, _>((|x: &i32| *x, |x: &i32| *x), &err), err,);
65	///
66	/// // Composition: bimap((compose(f1, f2), compose(g1, g2)), &p)
67	/// //            = bimap((f2, g2), &bimap((f1, g1), &p))
68	/// let f1 = |x: &i32| *x + 1;
69	/// let f2 = |x: &i32| *x * 2;
70	/// let g1 = |x: &i32| *x + 10;
71	/// let g2 = |x: &i32| *x * 3;
72	/// assert_eq!(
73	/// 	bimap::<ResultBrand, _, _, _, _, _, _>((|x: &i32| f2(&f1(x)), |x: &i32| g2(&g1(x))), &ok),
74	/// 	bimap::<ResultBrand, _, _, _, _, _, _>(
75	/// 		(f2, g2),
76	/// 		&bimap::<ResultBrand, _, _, _, _, _, _>((f1, g1), &ok),
77	/// 	),
78	/// );
79	/// ```
80	#[kind(type Of<'a, A: 'a, B: 'a>: 'a;)]
81	pub trait RefBifunctor {
82		/// Maps functions over the values in the bifunctor context by reference.
83		///
84		/// Both closures receive references to the values and produce owned output.
85		/// The container is borrowed, not consumed.
86		#[document_signature]
87		///
88		#[document_type_parameters(
89			"The lifetime of the values.",
90			"The type of the first value.",
91			"The type of the first result.",
92			"The type of the second value.",
93			"The type of the second result."
94		)]
95		///
96		#[document_parameters(
97			"The function to apply to the first value.",
98			"The function to apply to the second value.",
99			"The bifunctor instance (borrowed)."
100		)]
101		///
102		#[document_returns(
103			"A new bifunctor instance containing the results of applying the functions."
104		)]
105		#[document_examples]
106		///
107		/// ```
108		/// use fp_library::{
109		/// 	brands::*,
110		/// 	classes::*,
111		/// };
112		///
113		/// let x: Result<i32, i32> = Ok(5);
114		/// let y = ResultBrand::ref_bimap(|e: &i32| *e + 1, |s: &i32| *s * 2, &x);
115		/// assert_eq!(y, Ok(10));
116		/// ```
117		fn ref_bimap<'a, A: 'a, B: 'a, C: 'a, D: 'a>(
118			f: impl Fn(&A) -> B + 'a,
119			g: impl Fn(&C) -> D + 'a,
120			p: &Apply!(<Self as Kind!( type Of<'a, A: 'a, B: 'a>: 'a; )>::Of<'a, A, C>),
121		) -> Apply!(<Self as Kind!( type Of<'a, A: 'a, B: 'a>: 'a; )>::Of<'a, B, D>);
122	}
123
124	/// Maps functions over the values in the bifunctor context by reference.
125	///
126	/// Free function version that dispatches to [the type class' associated function][`RefBifunctor::ref_bimap`].
127	#[document_signature]
128	///
129	#[document_type_parameters(
130		"The lifetime of the values.",
131		"The brand of the bifunctor.",
132		"The type of the first value.",
133		"The type of the first result.",
134		"The type of the second value.",
135		"The type of the second result."
136	)]
137	///
138	#[document_parameters(
139		"The function to apply to the first value.",
140		"The function to apply to the second value.",
141		"The bifunctor instance (borrowed)."
142	)]
143	///
144	#[document_returns(
145		"A new bifunctor instance containing the results of applying the functions."
146	)]
147	#[document_examples]
148	///
149	/// ```
150	/// use fp_library::{
151	/// 	brands::*,
152	/// 	functions::explicit::*,
153	/// };
154	///
155	/// let x = Result::<i32, i32>::Ok(5);
156	/// let y = bimap::<ResultBrand, _, _, _, _, _, _>((|e: &i32| *e + 1, |s: &i32| *s * 2), &x);
157	/// assert_eq!(y, Ok(10));
158	/// ```
159	pub fn ref_bimap<'a, Brand: RefBifunctor, A: 'a, B: 'a, C: 'a, D: 'a>(
160		f: impl Fn(&A) -> B + 'a,
161		g: impl Fn(&C) -> D + 'a,
162		p: &Apply!(<Brand as Kind!( type Of<'a, A: 'a, B: 'a>: 'a; )>::Of<'a, A, C>),
163	) -> Apply!(<Brand as Kind!( type Of<'a, A: 'a, B: 'a>: 'a; )>::Of<'a, B, D>) {
164		Brand::ref_bimap(f, g, p)
165	}
166
167	/// [`RefFunctor`] instance for [`BifunctorFirstAppliedBrand`].
168	///
169	/// Maps over the first type parameter of a bifunctor by reference, delegating to
170	/// [`RefBifunctor::ref_bimap`] with [`Clone::clone`] for the second argument.
171	/// Requires `Clone` on the fixed second type parameter because the value must be
172	/// cloned out of the borrowed container.
173	#[document_type_parameters("The bifunctor brand.", "The fixed second type parameter.")]
174	impl<Brand: Bifunctor + RefBifunctor, A: Clone + 'static> RefFunctor
175		for BifunctorFirstAppliedBrand<Brand, A>
176	{
177		/// Maps a function over the first type parameter by reference.
178		#[document_signature]
179		#[document_type_parameters(
180			"The lifetime of the values.",
181			"The input type.",
182			"The output type."
183		)]
184		#[document_parameters("The function to apply.", "The bifunctor value to map over.")]
185		#[document_returns("The mapped bifunctor value.")]
186		#[document_examples]
187		///
188		/// ```
189		/// use fp_library::{
190		/// 	brands::*,
191		/// 	functions::explicit::*,
192		/// };
193		///
194		/// let x = Result::<i32, i32>::Ok(5);
195		/// let y = map::<BifunctorFirstAppliedBrand<ResultBrand, i32>, _, _, _, _>(|s: &i32| *s * 2, &x);
196		/// assert_eq!(y, Ok(10));
197		/// ```
198		fn ref_map<'a, B: 'a, C: 'a>(
199			func: impl Fn(&B) -> C + 'a,
200			fa: &Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>),
201		) -> Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, C>) {
202			Brand::ref_bimap(|a: &A| a.clone(), func, fa)
203		}
204	}
205
206	/// [`RefFunctor`] instance for [`BifunctorSecondAppliedBrand`].
207	///
208	/// Maps over the second type parameter of a bifunctor by reference, delegating to
209	/// [`RefBifunctor::ref_bimap`] with [`Clone::clone`] for the first argument.
210	/// Requires `Clone` on the fixed first type parameter because the value must be
211	/// cloned out of the borrowed container.
212	#[document_type_parameters("The bifunctor brand.", "The fixed first type parameter.")]
213	impl<Brand: Bifunctor + RefBifunctor, B: Clone + 'static> RefFunctor
214		for BifunctorSecondAppliedBrand<Brand, B>
215	{
216		/// Maps a function over the second type parameter by reference.
217		#[document_signature]
218		#[document_type_parameters(
219			"The lifetime of the values.",
220			"The input type.",
221			"The output type."
222		)]
223		#[document_parameters("The function to apply.", "The bifunctor value to map over.")]
224		#[document_returns("The mapped bifunctor value.")]
225		#[document_examples]
226		///
227		/// ```
228		/// use fp_library::{
229		/// 	brands::*,
230		/// 	functions::explicit::*,
231		/// };
232		///
233		/// let x = Result::<i32, i32>::Err(5);
234		/// let y = map::<BifunctorSecondAppliedBrand<ResultBrand, i32>, _, _, _, _>(|e: &i32| *e * 2, &x);
235		/// assert_eq!(y, Err(10));
236		/// ```
237		fn ref_map<'a, A: 'a, C: 'a>(
238			func: impl Fn(&A) -> C + 'a,
239			fa: &Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
240		) -> Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, C>) {
241			Brand::ref_bimap(func, |b: &B| b.clone(), fa)
242		}
243	}
244}
245
246pub use inner::*;
247
248#[cfg(test)]
249mod tests {
250	use {
251		crate::{
252			brands::*,
253			functions::explicit::*,
254		},
255		quickcheck_macros::quickcheck,
256	};
257
258	/// RefBifunctor identity law: bimap((Clone::clone, Clone::clone), &p) == p.
259	#[quickcheck]
260	fn prop_ref_bifunctor_identity(
261		a: i32,
262		c: i32,
263	) -> bool {
264		let ok: Result<i32, i32> = Ok(c);
265		let err: Result<i32, i32> = Err(a);
266		bimap::<ResultBrand, _, _, _, _, _, _>((|x: &i32| *x, |x: &i32| *x), &ok) == ok
267			&& bimap::<ResultBrand, _, _, _, _, _, _>((|x: &i32| *x, |x: &i32| *x), &err) == err
268	}
269
270	/// RefBifunctor composition law.
271	#[quickcheck]
272	fn prop_ref_bifunctor_composition(
273		a: i32,
274		c: i32,
275	) -> bool {
276		let f1 = |x: &i32| x.wrapping_add(1);
277		let f2 = |x: &i32| x.wrapping_mul(2);
278		let g1 = |x: &i32| x.wrapping_add(10);
279		let g2 = |x: &i32| x.wrapping_mul(3);
280
281		let ok: Result<i32, i32> = Ok(c);
282		let err: Result<i32, i32> = Err(a);
283
284		let composed_ok = bimap::<ResultBrand, _, _, _, _, _, _>(
285			(|x: &i32| f2(&f1(x)), |x: &i32| g2(&g1(x))),
286			&ok,
287		);
288		let sequential_ok = bimap::<ResultBrand, _, _, _, _, _, _>(
289			(f2, g2),
290			&bimap::<ResultBrand, _, _, _, _, _, _>((f1, g1), &ok),
291		);
292
293		let composed_err = bimap::<ResultBrand, _, _, _, _, _, _>(
294			(|x: &i32| f2(&f1(x)), |x: &i32| g2(&g1(x))),
295			&err,
296		);
297		let sequential_err = bimap::<ResultBrand, _, _, _, _, _, _>(
298			(f2, g2),
299			&bimap::<ResultBrand, _, _, _, _, _, _>((f1, g1), &err),
300		);
301
302		composed_ok == sequential_ok && composed_err == sequential_err
303	}
304}