Skip to main content

fp_library/classes/
profunctor.rs

1//! Profunctors, which are functors contravariant in the first argument and covariant in the second.
2//!
3//! A profunctor represents a morphism between two categories, mapping objects and morphisms from one to the other.
4//!
5//! ### Examples
6//!
7//! ```
8//! use fp_library::{
9//! 	brands::*,
10//! 	functions::*,
11//! };
12//!
13//! // Function is a profunctor
14//! let f = |x: i32| x + 1;
15//! let g = dimap::<RcFnBrand, _, _, _, _>(
16//! 	|x: i32| x * 2,
17//! 	|x: i32| x - 1,
18//! 	std::rc::Rc::new(f) as std::rc::Rc<dyn Fn(i32) -> i32>,
19//! );
20//! assert_eq!(g(10), 20); // (10 * 2) + 1 - 1 = 20
21//! ```
22
23pub use {
24	choice::*,
25	closed::*,
26	cochoice::*,
27	costrong::*,
28	strong::*,
29	wander::*,
30};
31
32pub mod choice;
33pub mod closed;
34pub mod cochoice;
35pub mod costrong;
36pub mod strong;
37pub mod wander;
38
39#[fp_macros::document_module]
40mod inner {
41	use {
42		crate::{
43			brands::*,
44			classes::*,
45			kinds::*,
46		},
47		fp_macros::*,
48	};
49
50	/// A type class for profunctors.
51	///
52	/// A profunctor is a type constructor that is contravariant in its first type parameter
53	/// and covariant in its second type parameter. This means it can pre-compose with a
54	/// function on the input and post-compose with a function on the output.
55	///
56	/// ### Hierarchy Unification
57	///
58	/// This trait is now the root of the unified profunctor and arrow hierarchies on
59	/// [`Kind!(type Of<'a, A: 'a, B: 'a>: 'a;)`](crate::kinds::Kind_266801a817966495).
60	/// This unification ensures that all profunctor-based abstractions
61	/// (including lenses and prisms) share a consistent higher-kinded representation with
62	/// strict lifetime bounds.
63	///
64	/// By explicitly requiring that both type parameters outlive the application lifetime `'a`,
65	/// we provide the compiler with the necessary guarantees to handle trait objects
66	/// (like `dyn Fn`) commonly used in profunctor implementations. This resolves potential
67	/// E0310 errors where the compiler cannot otherwise prove that captured variables in
68	/// closures satisfy the required lifetime bounds.
69	///
70	/// ### Laws
71	///
72	/// `Profunctor` instances must satisfy the following laws:
73	/// * Identity: `dimap(identity, identity, p) = p`.
74	/// * Composition: `dimap(f2 ∘ f1, g1 ∘ g2, p) = dimap(f1, g1, dimap(f2, g2, p))`.
75	#[document_examples]
76	///
77	/// Profunctor laws for [`RcFnBrand`](crate::brands::RcFnBrand):
78	///
79	/// ```
80	/// use fp_library::{
81	/// 	brands::*,
82	/// 	functions::*,
83	/// };
84	///
85	/// let p = std::rc::Rc::new(|x: i32| x + 1) as std::rc::Rc<dyn Fn(i32) -> i32>;
86	///
87	/// // Identity: dimap(identity, identity, p) = p
88	/// let id_mapped = dimap::<RcFnBrand, _, _, _, _>(identity, identity, p.clone());
89	/// assert_eq!(id_mapped(5), p(5));
90	/// assert_eq!(id_mapped(0), p(0));
91	///
92	/// // Composition: dimap(f2 ∘ f1, g1 ∘ g2, p)
93	/// //            = dimap(f1, g1, dimap(f2, g2, p))
94	/// let f1 = |x: i32| x + 10;
95	/// let f2 = |x: i32| x * 2;
96	/// let g1 = |x: i32| x - 1;
97	/// let g2 = |x: i32| x * 3;
98	/// let left = dimap::<RcFnBrand, _, _, _, _>(
99	/// 	compose(f2, f1), // f2 ∘ f1
100	/// 	compose(g1, g2), // g1 ∘ g2
101	/// 	p.clone(),
102	/// );
103	/// let right = dimap::<RcFnBrand, _, _, _, _>(f1, g1, dimap::<RcFnBrand, _, _, _, _>(f2, g2, p));
104	/// assert_eq!(left(5), right(5));
105	/// assert_eq!(left(0), right(0));
106	/// ```
107	#[kind(type Of<'a, A: 'a, B: 'a>: 'a;)]
108	pub trait Profunctor {
109		/// Maps over both arguments of the profunctor.
110		///
111		/// This method applies a contravariant function to the first argument and a covariant
112		/// function to the second argument, transforming the profunctor.
113		#[document_signature]
114		///
115		#[document_type_parameters(
116			"The lifetime of the values.",
117			"The new input type (contravariant position).",
118			"The original input type.",
119			"The original output type.",
120			"The new output type (covariant position)."
121		)]
122		///
123		#[document_parameters(
124			"The contravariant function to apply to the input.",
125			"The covariant function to apply to the output.",
126			"The profunctor instance."
127		)]
128		///
129		#[document_returns("A new profunctor instance with transformed input and output types.")]
130		#[document_examples]
131		///
132		/// ```
133		/// use fp_library::{
134		/// 	brands::*,
135		/// 	classes::profunctor::*,
136		/// 	functions::*,
137		/// };
138		///
139		/// let f = |x: i32| x + 1;
140		/// let g = dimap::<RcFnBrand, _, _, _, _>(
141		/// 	|x: i32| x * 2,
142		/// 	|x: i32| x - 1,
143		/// 	std::rc::Rc::new(f) as std::rc::Rc<dyn Fn(i32) -> i32>,
144		/// );
145		/// assert_eq!(g(10), 20); // (10 * 2) + 1 - 1 = 20
146		/// ```
147		fn dimap<'a, A: 'a, B: 'a, C: 'a, D: 'a>(
148			ab: impl Fn(A) -> B + 'a,
149			cd: impl Fn(C) -> D + 'a,
150			pbc: Apply!(<Self as Kind!( type Of<'a, T: 'a, U: 'a>: 'a; )>::Of<'a, B, C>),
151		) -> Apply!(<Self as Kind!( type Of<'a, T: 'a, U: 'a>: 'a; )>::Of<'a, A, D>);
152
153		/// Maps contravariantly over the first argument.
154		///
155		/// This is a convenience method that maps only over the input (contravariant position).
156		#[document_signature]
157		///
158		#[document_type_parameters(
159			"The lifetime of the values.",
160			"The new input type.",
161			"The original input type.",
162			"The output type."
163		)]
164		///
165		#[document_parameters(
166			"The contravariant function to apply to the input.",
167			"The profunctor instance."
168		)]
169		///
170		#[document_returns("A new profunctor instance with transformed input type.")]
171		#[document_examples]
172		///
173		/// ```
174		/// use fp_library::{
175		/// 	brands::*,
176		/// 	classes::profunctor::*,
177		/// 	functions::*,
178		/// };
179		///
180		/// let f = |x: i32| x + 1;
181		/// let g = lmap::<RcFnBrand, _, _, _>(
182		/// 	|x: i32| x * 2,
183		/// 	std::rc::Rc::new(f) as std::rc::Rc<dyn Fn(i32) -> i32>,
184		/// );
185		/// assert_eq!(g(10), 21); // (10 * 2) + 1 = 21
186		/// ```
187		fn lmap<'a, A: 'a, B: 'a, C: 'a>(
188			ab: impl Fn(A) -> B + 'a,
189			pbc: Apply!(<Self as Kind!( type Of<'a, T: 'a, U: 'a>: 'a; )>::Of<'a, B, C>),
190		) -> Apply!(<Self as Kind!( type Of<'a, T: 'a, U: 'a>: 'a; )>::Of<'a, A, C>) {
191			Self::dimap(ab, crate::functions::identity, pbc)
192		}
193
194		/// Maps covariantly over the second argument.
195		///
196		/// This is a convenience method that maps only over the output (covariant position).
197		#[document_signature]
198		///
199		#[document_type_parameters(
200			"The lifetime of the values.",
201			"The input type.",
202			"The original output type.",
203			"The new output type."
204		)]
205		///
206		#[document_parameters(
207			"The covariant function to apply to the output.",
208			"The profunctor instance."
209		)]
210		///
211		#[document_returns("A new profunctor instance with transformed output type.")]
212		#[document_examples]
213		///
214		/// ```
215		/// use fp_library::{
216		/// 	brands::*,
217		/// 	classes::profunctor::*,
218		/// 	functions::*,
219		/// };
220		///
221		/// let f = |x: i32| x + 1;
222		/// let g = rmap::<RcFnBrand, _, _, _>(
223		/// 	|x: i32| x * 2,
224		/// 	std::rc::Rc::new(f) as std::rc::Rc<dyn Fn(i32) -> i32>,
225		/// );
226		/// assert_eq!(g(10), 22); // (10 + 1) * 2 = 22
227		/// ```
228		fn rmap<'a, A: 'a, B: 'a, C: 'a>(
229			bc: impl Fn(B) -> C + 'a,
230			pab: Apply!(<Self as Kind!( type Of<'a, T: 'a, U: 'a>: 'a; )>::Of<'a, A, B>),
231		) -> Apply!(<Self as Kind!( type Of<'a, T: 'a, U: 'a>: 'a; )>::Of<'a, A, C>) {
232			Self::dimap(crate::functions::identity, bc, pab)
233		}
234	}
235
236	/// Maps over both arguments of the profunctor.
237	///
238	/// Free function version that dispatches to [the type class' associated function][`Profunctor::dimap`].
239	#[document_signature]
240	///
241	#[document_type_parameters(
242		"The lifetime of the values.",
243		"The brand of the profunctor.",
244		"The new input type (contravariant position).",
245		"The original input type.",
246		"The original output type.",
247		"The new output type (covariant position)."
248	)]
249	///
250	#[document_parameters(
251		"The contravariant function to apply to the input.",
252		"The covariant function to apply to the output.",
253		"The profunctor instance."
254	)]
255	///
256	#[document_returns("A new profunctor instance with transformed input and output types.")]
257	#[document_examples]
258	///
259	/// ```
260	/// use fp_library::{
261	/// 	brands::*,
262	/// 	classes::profunctor::*,
263	/// 	functions::*,
264	/// };
265	///
266	/// let f = |x: i32| x + 1;
267	/// let g = dimap::<RcFnBrand, _, _, _, _>(
268	/// 	|x: i32| x * 2,
269	/// 	|x: i32| x - 1,
270	/// 	std::rc::Rc::new(f) as std::rc::Rc<dyn Fn(i32) -> i32>,
271	/// );
272	/// assert_eq!(g(10), 20); // (10 * 2) + 1 - 1 = 20
273	/// ```
274	pub fn dimap<'a, Brand: Profunctor, A: 'a, B: 'a, C: 'a, D: 'a>(
275		ab: impl Fn(A) -> B + 'a,
276		cd: impl Fn(C) -> D + 'a,
277		pbc: Apply!(<Brand as Kind!( type Of<'a, T: 'a, U: 'a>: 'a; )>::Of<'a, B, C>),
278	) -> Apply!(<Brand as Kind!( type Of<'a, T: 'a, U: 'a>: 'a; )>::Of<'a, A, D>) {
279		Brand::dimap(ab, cd, pbc)
280	}
281
282	/// Maps contravariantly over the first argument.
283	///
284	/// Free function version that dispatches to [the type class' associated function][`Profunctor::lmap`].
285	#[document_signature]
286	///
287	#[document_type_parameters(
288		"The lifetime of the values.",
289		"The brand of the profunctor.",
290		"The new input type.",
291		"The original input type.",
292		"The output type."
293	)]
294	///
295	#[document_parameters(
296		"The contravariant function to apply to the input.",
297		"The profunctor instance."
298	)]
299	///
300	#[document_returns("A new profunctor instance with transformed input type.")]
301	#[document_examples]
302	///
303	/// ```
304	/// use fp_library::{
305	/// 	brands::*,
306	/// 	classes::profunctor::*,
307	/// 	functions::*,
308	/// };
309	///
310	/// let f = |x: i32| x + 1;
311	/// let g = lmap::<RcFnBrand, _, _, _>(
312	/// 	|x: i32| x * 2,
313	/// 	std::rc::Rc::new(f) as std::rc::Rc<dyn Fn(i32) -> i32>,
314	/// );
315	/// assert_eq!(g(10), 21); // (10 * 2) + 1 = 21
316	/// ```
317	pub fn lmap<'a, Brand: Profunctor, A: 'a, B: 'a, C: 'a>(
318		ab: impl Fn(A) -> B + 'a,
319		pbc: Apply!(<Brand as Kind!( type Of<'a, T: 'a, U: 'a>: 'a; )>::Of<'a, B, C>),
320	) -> Apply!(<Brand as Kind!( type Of<'a, T: 'a, U: 'a>: 'a; )>::Of<'a, A, C>) {
321		Brand::lmap(ab, pbc)
322	}
323
324	/// Maps covariantly over the second argument.
325	///
326	/// Free function version that dispatches to [the type class' associated function][`Profunctor::rmap`].
327	#[document_signature]
328	///
329	#[document_type_parameters(
330		"The lifetime of the values.",
331		"The brand of the profunctor.",
332		"The input type.",
333		"The original output type.",
334		"The new output type."
335	)]
336	///
337	#[document_parameters(
338		"The covariant function to apply to the output.",
339		"The profunctor instance."
340	)]
341	///
342	#[document_returns("A new profunctor instance with transformed output type.")]
343	#[document_examples]
344	///
345	/// ```
346	/// use fp_library::{
347	/// 	brands::*,
348	/// 	classes::profunctor::*,
349	/// 	functions::*,
350	/// };
351	///
352	/// let f = |x: i32| x + 1;
353	/// let g = rmap::<RcFnBrand, _, _, _>(
354	/// 	|x: i32| x * 2,
355	/// 	std::rc::Rc::new(f) as std::rc::Rc<dyn Fn(i32) -> i32>,
356	/// );
357	/// assert_eq!(g(10), 22); // (10 + 1) * 2 = 22
358	/// ```
359	pub fn rmap<'a, Brand: Profunctor, A: 'a, B: 'a, C: 'a>(
360		bc: impl Fn(B) -> C + 'a,
361		pab: Apply!(<Brand as Kind!( type Of<'a, T: 'a, U: 'a>: 'a; )>::Of<'a, A, B>),
362	) -> Apply!(<Brand as Kind!( type Of<'a, T: 'a, U: 'a>: 'a; )>::Of<'a, A, C>) {
363		Brand::rmap(bc, pab)
364	}
365
366	/// Lifts a pure function into a profunctor context.
367	///
368	/// Given a type that is both a [`Category`] (providing `identity`) and a
369	/// [`Profunctor`] (providing `rmap`), this function lifts a pure function
370	/// `A -> B` into the profunctor as `rmap(f, identity())`.
371	#[document_signature]
372	///
373	#[document_type_parameters(
374		"The lifetime of the function and its captured data.",
375		"The brand of the profunctor.",
376		"The input type.",
377		"The output type."
378	)]
379	///
380	#[document_parameters("The closure to lift.")]
381	///
382	#[document_returns("The lifted profunctor value.")]
383	#[document_examples]
384	///
385	/// ```
386	/// use fp_library::{
387	/// 	brands::*,
388	/// 	functions::*,
389	/// };
390	///
391	/// let f = arrow::<RcFnBrand, _, _>(|x: i32| x * 2);
392	/// assert_eq!(f(5), 10);
393	/// ```
394	pub fn arrow<'a, Brand, A, B: 'a>(
395		f: impl 'a + Fn(A) -> B
396	) -> Apply!(<Brand as Kind!( type Of<'a, T: 'a, U: 'a>: 'a; )>::Of<'a, A, B>)
397	where
398		Brand: Category + Profunctor, {
399		Brand::rmap(f, Brand::identity())
400	}
401
402	crate::impl_kind! {
403		impl<Brand: Profunctor, A: 'static> for ProfunctorFirstAppliedBrand<Brand, A> {
404			type Of<'a, B: 'a>: 'a = Apply!(<Brand as Kind!(type Of<'a, T: 'a, U: 'a>: 'a;)>::Of<'a, A, B>);
405		}
406	}
407
408	/// [`Functor`] instance for [`ProfunctorFirstAppliedBrand`].
409	///
410	/// Maps over the second (covariant) type parameter of a profunctor via [`Profunctor::rmap`].
411	#[document_type_parameters("The profunctor brand.", "The fixed first type parameter.")]
412	impl<Brand: Profunctor, A: 'static> Functor for ProfunctorFirstAppliedBrand<Brand, A> {
413		/// Map a function over the covariant type parameter.
414		#[document_signature]
415		#[document_type_parameters(
416			"The lifetime of the values.",
417			"The input type.",
418			"The output type."
419		)]
420		#[document_parameters("The function to apply.", "The profunctor value to map over.")]
421		#[document_returns("The mapped profunctor value.")]
422		#[document_examples]
423		///
424		/// ```
425		/// use fp_library::{
426		/// 	brands::*,
427		/// 	functions::*,
428		/// };
429		///
430		/// let f = std::rc::Rc::new(|x: i32| x + 1) as std::rc::Rc<dyn Fn(i32) -> i32>;
431		/// let g = map::<ProfunctorFirstAppliedBrand<RcFnBrand, i32>, _, _>(|x: i32| x * 2, f);
432		/// assert_eq!(g(5), 12); // (5 + 1) * 2
433		/// ```
434		fn map<'a, B: 'a, C: 'a>(
435			f: impl Fn(B) -> C + 'a,
436			fa: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>),
437		) -> Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, C>) {
438			Brand::rmap(f, fa)
439		}
440	}
441
442	impl_kind! {
443		impl<Brand: Profunctor, B: 'static> for ProfunctorSecondAppliedBrand<Brand, B> {
444			type Of<'a, A: 'a>: 'a = Apply!(<Brand as Kind!(type Of<'a, T: 'a, U: 'a>: 'a;)>::Of<'a, A, B>);
445		}
446	}
447
448	/// [`Contravariant`] instance for [`ProfunctorSecondAppliedBrand`].
449	///
450	/// Contramaps over the first (contravariant) type parameter of a profunctor via [`Profunctor::lmap`].
451	#[document_type_parameters("The profunctor brand.", "The fixed second type parameter.")]
452	impl<Brand: Profunctor, B: 'static> Contravariant for ProfunctorSecondAppliedBrand<Brand, B> {
453		/// Contramap a function over the contravariant type parameter.
454		#[document_signature]
455		#[document_type_parameters(
456			"The lifetime of the values.",
457			"The input type.",
458			"The output type."
459		)]
460		#[document_parameters("The function to apply.", "The profunctor value to contramap over.")]
461		#[document_returns("The contramapped profunctor value.")]
462		#[document_examples]
463		///
464		/// ```
465		/// use fp_library::{
466		/// 	brands::*,
467		/// 	functions::*,
468		/// };
469		///
470		/// let f = std::rc::Rc::new(|x: i32| x + 1) as std::rc::Rc<dyn Fn(i32) -> i32>;
471		/// let g = contramap::<ProfunctorSecondAppliedBrand<RcFnBrand, i32>, _, _>(|x: i32| x * 2, f);
472		/// assert_eq!(g(5), 11); // (5 * 2) + 1
473		/// ```
474		fn contramap<'a, A: 'a, C: 'a>(
475			f: impl Fn(C) -> A + 'a,
476			fa: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
477		) -> Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, C>) {
478			Brand::lmap(f, fa)
479		}
480	}
481}
482
483pub use inner::*;