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