Skip to main content

fp_library/classes/
traversable.rs

1//! Data structures that can be traversed, accumulating results in an applicative context.
2//!
3//! ### Examples
4//!
5//! ```
6//! use fp_library::{
7//! 	brands::*,
8//! 	functions::explicit::*,
9//! };
10//!
11//! let x = Some(5);
12//! let y = traverse::<RcFnBrand, OptionBrand, _, _, OptionBrand, _, _>(|a| Some(a * 2), x);
13//! assert_eq!(y, Some(Some(10)));
14//! ```
15
16#[fp_macros::document_module]
17mod inner {
18	use {
19		crate::{
20			classes::*,
21			functions::*,
22			kinds::*,
23		},
24		fp_macros::*,
25	};
26
27	/// A type class for traversable functors.
28	///
29	/// `Traversable` functors can be traversed, which accumulates results and effects in some [`Applicative`] context.
30	///
31	/// ### Laws
32	///
33	/// `Traversable` instances must satisfy:
34	/// * Traverse/sequence consistency: `traverse(f, xs) = sequence(map(f, xs))`.
35	/// * Sequence/traverse consistency: `sequence(xs) = traverse(identity, xs)`.
36	#[document_examples]
37	///
38	/// Traversable laws for [`Vec`]:
39	///
40	/// ```
41	/// use fp_library::{
42	/// 	brands::*,
43	/// 	functions::{
44	/// 		explicit::{
45	/// 			map,
46	/// 			traverse,
47	/// 		},
48	/// 		*,
49	/// 	},
50	/// };
51	///
52	/// let xs = vec![1, 2, 3];
53	/// let f = |a: i32| if a > 0 { Some(a * 2) } else { None };
54	///
55	/// // Traverse/sequence consistency:
56	/// // traverse(f, xs) = sequence(map(f, xs))
57	/// assert_eq!(
58	/// 	traverse::<RcFnBrand, VecBrand, _, _, OptionBrand, _, _>(f, xs.clone()),
59	/// 	sequence::<VecBrand, _, OptionBrand>(map::<VecBrand, _, _, _, _>(f, xs.clone())),
60	/// );
61	///
62	/// // Sequence/traverse consistency:
63	/// // sequence(xs) = traverse(identity, xs)
64	/// let ys: Vec<Option<i32>> = vec![Some(1), Some(2), Some(3)];
65	/// assert_eq!(
66	/// 	sequence::<VecBrand, _, OptionBrand>(ys.clone()),
67	/// 	traverse::<RcFnBrand, VecBrand, _, _, OptionBrand, _, _>(identity, ys),
68	/// );
69	/// ```
70	pub trait Traversable: Functor + Foldable {
71		/// Map each element of the [`Traversable`] structure to a computation, evaluate those computations and combine the results into an [`Applicative`] context.
72		///
73		/// The default implementation is defined in terms of [`sequence`] and [`map`](crate::functions::map).
74		///
75		/// **Note**: This default implementation may be less efficient than a direct implementation because it performs two passes:
76		/// first mapping the function to create an intermediate structure of computations, and then sequencing that structure.
77		/// A direct implementation can often perform the traversal in a single pass without allocating an intermediate container.
78		/// Types should provide their own implementation if possible.
79		#[document_signature]
80		///
81		#[document_type_parameters(
82			"The lifetime of the elements.",
83			"The type of the elements in the traversable structure.",
84			"The type of the elements in the resulting traversable structure.",
85			"The applicative context."
86		)]
87		///
88		#[document_parameters(
89			"The function to apply to each element, returning a value in an applicative context.",
90			"The traversable structure."
91		)]
92		///
93		#[document_returns("The traversable structure wrapped in the applicative context.")]
94		#[document_examples]
95		///
96		/// ```
97		/// use fp_library::{
98		/// 	brands::*,
99		/// 	functions::explicit::*,
100		/// };
101		///
102		/// let x = Some(5);
103		/// let y = traverse::<RcFnBrand, OptionBrand, _, _, OptionBrand, _, _>(|a| Some(a * 2), x);
104		/// assert_eq!(y, Some(Some(10)));
105		/// ```
106		fn traverse<'a, A: 'a + Clone, B: 'a + Clone, F: Applicative>(
107			func: impl Fn(A) -> Apply!(<F as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>) + 'a,
108			ta: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
109		) -> Apply!(<F as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>)>)
110		where
111			Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>): Clone,
112			Apply!(<F as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>): Clone, {
113			Self::sequence::<B, F>(Self::map::<
114				A,
115				Apply!(<F as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>),
116			>(func, ta))
117		}
118
119		/// Evaluate each computation in a [`Traversable`] structure and accumulate the results into an [`Applicative`] context.
120		///
121		/// The default implementation is defined in terms of [`traverse`] and [`identity`].
122		#[document_signature]
123		///
124		#[document_type_parameters(
125			"The lifetime of the elements.",
126			"The type of the elements in the traversable structure.",
127			"The applicative context."
128		)]
129		///
130		#[document_parameters(
131			"The traversable structure containing values in an applicative context."
132		)]
133		///
134		#[document_returns("The traversable structure wrapped in the applicative context.")]
135		#[document_examples]
136		///
137		/// ```
138		/// use fp_library::{
139		/// 	brands::*,
140		/// 	functions::*,
141		/// };
142		///
143		/// let x = Some(Some(5));
144		/// let y = sequence::<OptionBrand, _, OptionBrand>(x);
145		/// assert_eq!(y, Some(Some(5)));
146		/// ```
147		fn sequence<'a, A: 'a + Clone, F: Applicative>(
148			ta: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, Apply!(<F as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>)>)
149		) -> Apply!(<F as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>)>)
150		where
151			Apply!(<F as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>): Clone,
152			Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>): Clone, {
153			Self::traverse::<Apply!(<F as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>), A, F>(
154				identity, ta,
155			)
156		}
157	}
158
159	/// Map each element of the [`Traversable`] structure to a computation, evaluate those computations and combine the results into an [`Applicative`] context.
160	///
161	/// Free function version that dispatches to [the type class' associated function][`Traversable::traverse`].
162	#[document_signature]
163	///
164	#[document_type_parameters(
165		"The lifetime of the elements.",
166		"The brand of the traversable structure.",
167		"The type of the elements in the traversable structure.",
168		"The type of the elements in the resulting traversable structure.",
169		"The applicative context."
170	)]
171	///
172	#[document_parameters(
173		"The function to apply to each element, returning a value in an applicative context.",
174		"The traversable structure."
175	)]
176	///
177	#[document_returns("The traversable structure wrapped in the applicative context.")]
178	#[document_examples]
179	///
180	/// ```
181	/// use fp_library::{
182	/// 	brands::*,
183	/// 	functions::explicit::*,
184	/// };
185	///
186	/// let x = Some(5);
187	/// let y = traverse::<RcFnBrand, OptionBrand, _, _, OptionBrand, _, _>(|a| Some(a * 2), x);
188	/// assert_eq!(y, Some(Some(10)));
189	/// ```
190	pub fn traverse<'a, Brand: Traversable, A: 'a + Clone, B: 'a + Clone, F: Applicative>(
191		func: impl Fn(A) -> Apply!(<F as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>) + 'a,
192		ta: Apply!(<Brand as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
193	) -> Apply!(<F as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, Apply!(<Brand as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>)>)
194	where
195		Apply!(<Brand as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>): Clone,
196		Apply!(<F as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>): Clone, {
197		Brand::traverse::<A, B, F>(func, ta)
198	}
199
200	/// Evaluate each computation in a [`Traversable`] structure and accumulate the results into an [`Applicative`] context.
201	///
202	/// Free function version that dispatches to [the type class' associated function][`Traversable::sequence`].
203	#[document_signature]
204	///
205	#[document_type_parameters(
206		"The lifetime of the elements.",
207		"The brand of the traversable structure.",
208		"The type of the elements in the traversable structure.",
209		"The applicative context."
210	)]
211	///
212	#[document_parameters("The traversable structure containing values in an applicative context.")]
213	///
214	#[document_returns("The traversable structure wrapped in the applicative context.")]
215	#[document_examples]
216	///
217	/// ```
218	/// use fp_library::{
219	/// 	brands::*,
220	/// 	functions::*,
221	/// };
222	///
223	/// let x = Some(Some(5));
224	/// let y = sequence::<OptionBrand, _, OptionBrand>(x);
225	/// assert_eq!(y, Some(Some(5)));
226	/// ```
227	pub fn sequence<'a, Brand: Traversable, A: 'a + Clone, F: Applicative>(
228		ta: Apply!(<Brand as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, Apply!(<F as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>)>)
229	) -> Apply!(<F as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, Apply!(<Brand as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>)>)
230	where
231		Apply!(<F as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>): Clone,
232		Apply!(<Brand as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>): Clone, {
233		Brand::sequence::<A, F>(ta)
234	}
235}
236
237pub use inner::*;