Skip to main content

fp_library/types/
result.rs

1//! Functional programming trait implementations for the standard library [`Result`] type.
2//!
3//! Extends `Result` with dual functor/monad instances: [`ResultWithErrBrand`] (standard Result monad) functors over the success value, while [`ResultWithOkBrand`] functors over the error value.
4
5use crate::{
6	Apply,
7	brands::{ResultBrand, ResultWithErrBrand, ResultWithOkBrand},
8	classes::{
9		Applicative, ApplyFirst, ApplySecond, Bifunctor, CloneableFn, Foldable, Functor, Lift,
10		Monoid, ParFoldable, Pointed, Semiapplicative, Semimonad, SendCloneableFn, Traversable,
11	},
12	impl_kind,
13	kinds::*,
14};
15use fp_macros::{doc_params, doc_type_params, hm_signature};
16
17impl_kind! {
18	for ResultBrand {
19		type Of<A, B> = Result<B, A>;
20	}
21}
22
23impl_kind! {
24	for ResultBrand {
25		type Of<'a, A: 'a, B: 'a>: 'a = Result<B, A>;
26	}
27}
28
29impl Bifunctor for ResultBrand {
30	/// Maps functions over the values in the result.
31	///
32	/// This method applies one function to the error value and another to the success value.
33	///
34	/// ### Type Signature
35	///
36	#[hm_signature(Bifunctor)]
37	///
38	/// ### Type Parameters
39	///
40	#[doc_type_params(
41		"The lifetime of the values.",
42		"The type of the error value.",
43		"The type of the mapped error value.",
44		"The type of the success value.",
45		"The type of the mapped success value.",
46		"The type of the function to apply to the error.",
47		"The type of the function to apply to the success."
48	)]
49	///
50	/// ### Parameters
51	///
52	#[doc_params(
53		"The function to apply to the error.",
54		"The function to apply to the success.",
55		"The result to map over."
56	)]
57	///
58	/// ### Returns
59	///
60	/// A new result containing the mapped values.
61	///
62	/// ### Examples
63	///
64	/// ```
65	/// use fp_library::{brands::*, classes::bifunctor::*, functions::*};
66	///
67	/// let x: Result<i32, i32> = Ok(5);
68	/// assert_eq!(bimap::<ResultBrand, _, _, _, _, _, _>(|e| e + 1, |s| s * 2, x), Ok(10));
69	///
70	/// let y: Result<i32, i32> = Err(5);
71	/// assert_eq!(bimap::<ResultBrand, _, _, _, _, _, _>(|e| e + 1, |s| s * 2, y), Err(6));
72	/// ```
73	fn bimap<'a, A: 'a, B: 'a, C: 'a, D: 'a, F, G>(
74		f: F,
75		g: G,
76		p: Apply!(<Self as Kind!( type Of<'a, A: 'a, B: 'a>: 'a; )>::Of<'a, A, C>),
77	) -> Apply!(<Self as Kind!( type Of<'a, A: 'a, B: 'a>: 'a; )>::Of<'a, B, D>)
78	where
79		F: Fn(A) -> B + 'a,
80		G: Fn(C) -> D + 'a,
81	{
82		match p {
83			Ok(c) => Ok(g(c)),
84			Err(a) => Err(f(a)),
85		}
86	}
87}
88
89// ResultWithErrBrand<E> (Functor over T)
90
91impl_kind! {
92	impl<E: 'static> for ResultWithErrBrand<E> {
93		type Of<'a, A: 'a>: 'a = Result<A, E>;
94	}
95}
96
97impl<E: 'static> Functor for ResultWithErrBrand<E> {
98	/// Maps a function over the value in the result.
99	///
100	/// This method applies a function to the value inside the result if it is `Ok`, producing a new result with the transformed value. If the result is `Err`, it is returned unchanged.
101	///
102	/// ### Type Signature
103	///
104	#[hm_signature(Functor)]
105	///
106	/// ### Type Parameters
107	///
108	#[doc_type_params(
109		"The lifetime of the values.",
110		"The type of the value inside the result.",
111		"The type of the result of applying the function.",
112		"The type of the function to apply."
113	)]
114	///
115	/// ### Parameters
116	///
117	#[doc_params("The function to apply.", "The result to map over.")]
118	///
119	/// ### Returns
120	///
121	/// A new result containing the result of applying the function, or the original error.
122	///
123	/// ### Examples
124	///
125	/// ```
126	/// use fp_library::{brands::*, functions::*};
127	///
128	/// assert_eq!(map::<ResultWithErrBrand<()>, _, _, _>(|x: i32| x * 2, Ok(5)), Ok(10));
129	/// assert_eq!(map::<ResultWithErrBrand<i32>, _, _, _>(|x: i32| x * 2, Err(1)), Err(1));
130	/// ```
131	fn map<'a, A: 'a, B: 'a, Func>(
132		func: Func,
133		fa: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
134	) -> Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>)
135	where
136		Func: Fn(A) -> B + 'a,
137	{
138		fa.map(func)
139	}
140}
141
142impl<E: Clone + 'static> Lift for ResultWithErrBrand<E> {
143	/// Lifts a binary function into the result context.
144	///
145	/// This method lifts a binary function to operate on values within the result context.
146	///
147	/// ### Type Signature
148	///
149	#[hm_signature(Lift)]
150	///
151	/// ### Type Parameters
152	///
153	#[doc_type_params(
154		"The lifetime of the values.",
155		"The type of the first value.",
156		"The type of the second value.",
157		"The type of the result.",
158		"The type of the binary function."
159	)]
160	///
161	/// ### Parameters
162	///
163	#[doc_params("The binary function to apply.", "The first result.", "The second result.")]
164	///
165	/// ### Returns
166	///
167	/// `Ok(f(a, b))` if both results are `Ok`, otherwise the first error encountered.
168	///
169	/// ### Examples
170	///
171	/// ```
172	/// use fp_library::{brands::*, functions::*};
173	///
174	/// assert_eq!(
175	///     lift2::<ResultWithErrBrand<()>, _, _, _, _>(|x: i32, y: i32| x + y, Ok(1), Ok(2)),
176	///     Ok(3)
177	/// );
178	/// assert_eq!(
179	///     lift2::<ResultWithErrBrand<i32>, _, _, _, _>(|x: i32, y: i32| x + y, Ok(1), Err(2)),
180	///     Err(2)
181	/// );
182	/// assert_eq!(
183	///     lift2::<ResultWithErrBrand<i32>, _, _, _, _>(|x: i32, y: i32| x + y, Err(1), Ok(2)),
184	///     Err(1)
185	/// );
186	/// assert_eq!(
187	///     lift2::<ResultWithErrBrand<i32>, _, _, _, _>(|x: i32, y: i32| x + y, Err(1), Err(2)),
188	///     Err(1)
189	/// );
190	/// ```
191	fn lift2<'a, A, B, C, Func>(
192		func: Func,
193		fa: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
194		fb: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>),
195	) -> Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, C>)
196	where
197		Func: Fn(A, B) -> C + 'a,
198		A: Clone + 'a,
199		B: Clone + 'a,
200		C: 'a,
201	{
202		match (fa, fb) {
203			(Ok(a), Ok(b)) => Ok(func(a, b)),
204			(Err(e), _) => Err(e),
205			(_, Err(e)) => Err(e),
206		}
207	}
208}
209
210impl<E: 'static> Pointed for ResultWithErrBrand<E> {
211	/// Wraps a value in a result.
212	///
213	/// This method wraps a value in the `Ok` variant of a `Result`.
214	///
215	/// ### Type Signature
216	///
217	#[hm_signature(Pointed)]
218	///
219	/// ### Type Parameters
220	///
221	#[doc_type_params("The lifetime of the value.", "The type of the value to wrap.")]
222	///
223	/// ### Parameters
224	///
225	#[doc_params("The value to wrap.")]
226	///
227	/// ### Returns
228	///
229	/// `Ok(a)`.
230	///
231	/// ### Examples
232	///
233	/// ```
234	/// use fp_library::functions::*;
235	/// use fp_library::brands::ResultWithErrBrand;
236	///
237	/// assert_eq!(pure::<ResultWithErrBrand<()>, _>(5), Ok(5));
238	/// ```
239	fn pure<'a, A: 'a>(a: A) -> Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>) {
240		Ok(a)
241	}
242}
243
244impl<E: Clone + 'static> ApplyFirst for ResultWithErrBrand<E> {}
245impl<E: Clone + 'static> ApplySecond for ResultWithErrBrand<E> {}
246
247impl<E: Clone + 'static> Semiapplicative for ResultWithErrBrand<E> {
248	/// Applies a wrapped function to a wrapped value.
249	///
250	/// This method applies a function wrapped in a result to a value wrapped in a result.
251	///
252	/// ### Type Signature
253	///
254	#[hm_signature(Semiapplicative)]
255	///
256	/// ### Type Parameters
257	///
258	#[doc_type_params(
259		"The lifetime of the values.",
260		"The brand of the cloneable function wrapper.",
261		"The type of the input value.",
262		"The type of the output value."
263	)]
264	///
265	/// ### Parameters
266	///
267	#[doc_params("The result containing the function.", "The result containing the value.")]
268	///
269	/// ### Returns
270	///
271	/// `Ok(f(a))` if both are `Ok`, otherwise the first error encountered.
272	///
273	/// ### Examples
274	///
275	/// ```
276	/// use fp_library::{brands::*, classes::*, functions::*, Apply, Kind};
277	///
278	/// let f: Result<_, ()> = Ok(cloneable_fn_new::<RcFnBrand, _, _>(|x: i32| x * 2));
279	/// assert_eq!(apply::<RcFnBrand, ResultWithErrBrand<()>, _, _>(f, Ok(5)), Ok(10));
280	/// let f: Result<_, i32> = Ok(cloneable_fn_new::<RcFnBrand, _, _>(|x: i32| x * 2));
281	/// assert_eq!(apply::<RcFnBrand, ResultWithErrBrand<i32>, _, _>(f, Err(1)), Err(1));
282	///
283	/// let f_err: Result<_, i32> = Err(1);
284	/// assert_eq!(apply::<RcFnBrand, ResultWithErrBrand<i32>, i32, i32>(f_err, Ok(5)), Err(1));
285	/// ```
286	fn apply<'a, FnBrand: 'a + CloneableFn, A: 'a + Clone, B: 'a>(
287		ff: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, <FnBrand as CloneableFn>::Of<'a, A, B>>),
288		fa: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
289	) -> Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>) {
290		match (ff, fa) {
291			(Ok(f), Ok(a)) => Ok(f(a)),
292			(Err(e), _) => Err(e),
293			(_, Err(e)) => Err(e),
294		}
295	}
296}
297
298impl<E: Clone + 'static> Semimonad for ResultWithErrBrand<E> {
299	/// Chains result computations.
300	///
301	/// This method chains two computations, where the second computation depends on the result of the first.
302	///
303	/// ### Type Signature
304	///
305	#[hm_signature(Semimonad)]
306	///
307	/// ### Type Parameters
308	///
309	#[doc_type_params(
310		"The lifetime of the values.",
311		"The type of the result of the first computation.",
312		"The type of the result of the second computation.",
313		"The type of the function to apply."
314	)]
315	///
316	/// ### Parameters
317	///
318	#[doc_params("The first result.", "The function to apply to the value inside the result.")]
319	///
320	/// ### Returns
321	///
322	/// The result of applying `f` to the value if `ma` is `Ok`, otherwise the original error.
323	///
324	/// ### Examples
325	///
326	/// ```
327	/// use fp_library::functions::*;
328	/// use fp_library::brands::ResultWithErrBrand;
329	///
330	/// assert_eq!(
331	///     bind::<ResultWithErrBrand<()>, _, _, _>(Ok(5), |x| Ok(x * 2)),
332	///     Ok(10)
333	/// );
334	/// assert_eq!(
335	///     bind::<ResultWithErrBrand<i32>, _, _, _>(Ok(5), |_| Err::<i32, _>(1)),
336	///     Err(1)
337	/// );
338	/// assert_eq!(
339	///     bind::<ResultWithErrBrand<i32>, _, _, _>(Err(1), |x: i32| Ok(x * 2)),
340	///     Err(1)
341	/// );
342	/// ```
343	fn bind<'a, A: 'a, B: 'a, Func>(
344		ma: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
345		func: Func,
346	) -> Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>)
347	where
348		Func: Fn(A) -> Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>) + 'a,
349	{
350		ma.and_then(func)
351	}
352}
353
354impl<E: 'static> Foldable for ResultWithErrBrand<E> {
355	/// Folds the result from the right.
356	///
357	/// This method performs a right-associative fold of the result.
358	///
359	/// ### Type Signature
360	///
361	#[hm_signature(Foldable)]
362	///
363	/// ### Type Parameters
364	///
365	#[doc_type_params(
366		"The lifetime of the values.",
367		"The brand of the cloneable function to use.",
368		"The type of the elements in the structure.",
369		"The type of the accumulator.",
370		"The type of the folding function."
371	)]
372	///
373	/// ### Parameters
374	///
375	#[doc_params("The folding function.", "The initial value.", "The result to fold.")]
376	///
377	/// ### Returns
378	///
379	/// `func(a, initial)` if `fa` is `Ok(a)`, otherwise `initial`.
380	///
381	/// ### Examples
382	///
383	/// ```
384	/// use fp_library::{brands:: *, functions::*};
385	///
386	/// assert_eq!(fold_right::<RcFnBrand, ResultWithErrBrand<()>, _, _, _>(|x, acc| x + acc, 0, Ok(5)), 5);
387	/// assert_eq!(fold_right::<RcFnBrand, ResultWithErrBrand<i32>, _, _, _>(|x: i32, acc| x + acc, 0, Err(1)), 0);
388	/// ```
389	fn fold_right<'a, FnBrand, A: 'a, B: 'a, F>(
390		func: F,
391		initial: B,
392		fa: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
393	) -> B
394	where
395		F: Fn(A, B) -> B + 'a,
396		FnBrand: CloneableFn + 'a,
397	{
398		match fa {
399			Ok(a) => func(a, initial),
400			Err(_) => initial,
401		}
402	}
403
404	/// Folds the result from the left.
405	///
406	/// This method performs a left-associative fold of the result.
407	///
408	/// ### Type Signature
409	///
410	#[hm_signature(Foldable)]
411	///
412	/// ### Type Parameters
413	///
414	#[doc_type_params(
415		"The lifetime of the values.",
416		"The brand of the cloneable function to use.",
417		"The type of the elements in the structure.",
418		"The type of the accumulator.",
419		"The type of the folding function."
420	)]
421	///
422	/// ### Parameters
423	///
424	#[doc_params("The folding function.", "The initial value.", "The result to fold.")]
425	///
426	/// ### Returns
427	///
428	/// `func(initial, a)` if `fa` is `Ok(a)`, otherwise `initial`.
429	///
430	/// ### Examples
431	///
432	/// ```
433	/// use fp_library::{brands:: *, functions::*};
434	///
435	/// assert_eq!(fold_left::<RcFnBrand, ResultWithErrBrand<()>, _, _, _>(|acc, x| acc + x, 0, Ok(5)), 5);
436	/// assert_eq!(fold_left::<RcFnBrand, ResultWithErrBrand<i32>, _, _, _>(|acc, x: i32| acc + x, 0, Err(1)), 0);
437	/// ```
438	fn fold_left<'a, FnBrand, A: 'a, B: 'a, F>(
439		func: F,
440		initial: B,
441		fa: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
442	) -> B
443	where
444		F: Fn(B, A) -> B + 'a,
445		FnBrand: CloneableFn + 'a,
446	{
447		match fa {
448			Ok(a) => func(initial, a),
449			Err(_) => initial,
450		}
451	}
452
453	/// Maps the value to a monoid and returns it.
454	///
455	/// This method maps the element of the result to a monoid and then returns it.
456	///
457	/// ### Type Signature
458	///
459	#[hm_signature(Foldable)]
460	///
461	/// ### Type Parameters
462	///
463	#[doc_type_params(
464		"The lifetime of the values.",
465		"The brand of the cloneable function to use.",
466		"The type of the elements in the structure.",
467		"The type of the monoid.",
468		"The type of the mapping function."
469	)]
470	///
471	/// ### Parameters
472	///
473	#[doc_params("The mapping function.", "The result to fold.")]
474	///
475	/// ### Returns
476	///
477	/// `func(a)` if `fa` is `Ok(a)`, otherwise `M::empty()`.
478	///
479	/// ### Examples
480	///
481	/// ```
482	/// use fp_library::{brands::*, functions::*};
483	///
484	/// assert_eq!(
485	///     fold_map::<RcFnBrand, ResultWithErrBrand<()>, _, _, _>(|x: i32| x.to_string(), Ok(5)),
486	///     "5".to_string()
487	/// );
488	/// assert_eq!(
489	///     fold_map::<RcFnBrand, ResultWithErrBrand<i32>, _, _, _>(|x: i32| x.to_string(), Err(1)),
490	///     "".to_string()
491	/// );
492	/// ```
493	fn fold_map<'a, FnBrand, A: 'a, M, F>(
494		func: F,
495		fa: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
496	) -> M
497	where
498		M: Monoid + 'a,
499		F: Fn(A) -> M + 'a,
500		FnBrand: CloneableFn + 'a,
501	{
502		match fa {
503			Ok(a) => func(a),
504			Err(_) => M::empty(),
505		}
506	}
507}
508
509impl<E: Clone + 'static> Traversable for ResultWithErrBrand<E> {
510	/// Traverses the result with an applicative function.
511	///
512	/// This method maps the element of the result to a computation, evaluates it, and combines the result into an applicative context.
513	///
514	/// ### Type Signature
515	///
516	#[hm_signature(Traversable)]
517	///
518	/// ### Type Parameters
519	///
520	#[doc_type_params(
521		"The lifetime of the values.",
522		"The type of the elements in the traversable structure.",
523		"The type of the elements in the resulting traversable structure.",
524		"The applicative context.",
525		"The type of the function to apply."
526	)]
527	///
528	/// ### Parameters
529	///
530	#[doc_params("The function to apply.", "The result to traverse.")]
531	///
532	/// ### Returns
533	///
534	/// The result wrapped in the applicative context.
535	///
536	/// ### Examples
537	///
538	/// ```
539	/// use fp_library::functions::*;
540	/// use fp_library::brands::{ResultWithErrBrand, OptionBrand};
541	///
542	/// assert_eq!(
543	///     traverse::<ResultWithErrBrand<()>, _, _, OptionBrand, _>(|x| Some(x * 2), Ok(5)),
544	///     Some(Ok(10))
545	/// );
546	/// assert_eq!(
547	///     traverse::<ResultWithErrBrand<i32>, _, _, OptionBrand, _>(|x: i32| Some(x * 2), Err(1)),
548	///     Some(Err(1))
549	/// );
550	/// assert_eq!(
551	///     traverse::<ResultWithErrBrand<()>, _, _, OptionBrand, _>(|_| None::<i32>, Ok(5)),
552	///     None
553	/// );
554	/// ```
555	fn traverse<'a, A: 'a + Clone, B: 'a + Clone, F: Applicative, Func>(
556		func: Func,
557		ta: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
558	) -> 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>)>)
559	where
560		Func: Fn(A) -> Apply!(<F as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>) + 'a,
561		Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>): Clone,
562	{
563		match ta {
564			Ok(a) => F::map(|b| Ok(b), func(a)),
565			Err(e) => F::pure(Err(e)),
566		}
567	}
568
569	/// Sequences a result of applicative.
570	///
571	/// This method evaluates the computation inside the result and accumulates the result into an applicative context.
572	///
573	/// ### Type Signature
574	///
575	#[hm_signature(Traversable)]
576	///
577	/// ### Type Parameters
578	///
579	#[doc_type_params(
580		"The lifetime of the values.",
581		"The type of the elements in the traversable structure.",
582		"The applicative context."
583	)]
584	///
585	/// ### Parameters
586	///
587	#[doc_params("The result containing the applicative value.")]
588	///
589	/// ### Returns
590	///
591	/// The result wrapped in the applicative context.
592	///
593	/// ### Examples
594	///
595	/// ```
596	/// use fp_library::functions::*;
597	/// use fp_library::brands::{ResultWithErrBrand, OptionBrand};
598	///
599	/// assert_eq!(
600	///     sequence::<ResultWithErrBrand<()>, _, OptionBrand>(Ok(Some(5))),
601	///     Some(Ok(5))
602	/// );
603	/// assert_eq!(
604	///     sequence::<ResultWithErrBrand<i32>, i32, OptionBrand>(Err::<Option<i32>, _>(1)),
605	///     Some(Err::<i32, i32>(1))
606	/// );
607	/// assert_eq!(
608	///     sequence::<ResultWithErrBrand<()>, _, OptionBrand>(Ok(None::<i32>)),
609	///     None
610	/// );
611	/// ```
612	fn sequence<'a, A: 'a + Clone, F: Applicative>(
613		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>)>)
614	) -> 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>)>)
615	where
616		Apply!(<F as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>): Clone,
617		Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>): Clone,
618	{
619		match ta {
620			Ok(fa) => F::map(|a| Ok(a), fa),
621			Err(e) => F::pure(Err(e)),
622		}
623	}
624}
625
626// ResultWithOkBrand<T> (Functor over E)
627
628impl_kind! {
629	impl<T: 'static> for ResultWithOkBrand<T> {
630		type Of<'a, A: 'a>: 'a = Result<T, A>;
631	}
632}
633
634impl<T: 'static> Functor for ResultWithOkBrand<T> {
635	/// Maps a function over the error value in the result.
636	///
637	/// This method applies a function to the error value inside the result if it is `Err`, producing a new result with the transformed error. If the result is `Ok`, it is returned unchanged.
638	///
639	/// ### Type Signature
640	///
641	#[hm_signature(Functor)]
642	///
643	/// ### Type Parameters
644	///
645	#[doc_type_params(
646		"The lifetime of the values.",
647		"The type of the error value inside the result.",
648		"The type of the result of applying the function.",
649		"The type of the function to apply."
650	)]
651	///
652	/// ### Parameters
653	///
654	#[doc_params("The function to apply to the error.", "The result to map over.")]
655	///
656	/// ### Returns
657	///
658	/// A new result containing the mapped error, or the original success value.
659	///
660	/// ### Examples
661	///
662	/// ```
663	/// use fp_library::{brands::*, functions::*};
664	///
665	/// assert_eq!(map::<ResultWithOkBrand<i32>, _, _, _>(|x: i32| x * 2, Err(5)), Err(10));
666	/// assert_eq!(map::<ResultWithOkBrand<i32>, _, _, _>(|x: i32| x * 2, Ok(1)), Ok(1));
667	/// ```
668	fn map<'a, A: 'a, B: 'a, Func>(
669		func: Func,
670		fa: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
671	) -> Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>)
672	where
673		Func: Fn(A) -> B + 'a,
674	{
675		match fa {
676			Ok(t) => Ok(t),
677			Err(e) => Err(func(e)),
678		}
679	}
680}
681
682impl<T: Clone + 'static> Lift for ResultWithOkBrand<T> {
683	/// Lifts a binary function into the result context (over error).
684	///
685	/// This method lifts a binary function to operate on error values within the result context.
686	///
687	/// ### Type Signature
688	///
689	#[hm_signature(Lift)]
690	///
691	/// ### Type Parameters
692	///
693	#[doc_type_params(
694		"The lifetime of the values.",
695		"The type of the first error value.",
696		"The type of the second error value.",
697		"The type of the result error value.",
698		"The type of the binary function."
699	)]
700	///
701	/// ### Parameters
702	///
703	#[doc_params(
704		"The binary function to apply to the errors.",
705		"The first result.",
706		"The second result."
707	)]
708	///
709	/// ### Returns
710	///
711	/// `Err(f(a, b))` if both results are `Err`, otherwise the first success encountered.
712	///
713	/// ### Examples
714	///
715	/// ```
716	/// use fp_library::{brands::*, functions::*};
717	///
718	/// assert_eq!(
719	///     lift2::<ResultWithOkBrand<i32>, _, _, _, _>(|x: i32, y: i32| x + y, Err(1), Err(2)),
720	///     Err(3)
721	/// );
722	/// assert_eq!(
723	///     lift2::<ResultWithOkBrand<i32>, _, _, _, _>(|x: i32, y: i32| x + y, Err(1), Ok(2)),
724	///     Ok(2)
725	/// );
726	/// assert_eq!(
727	///     lift2::<ResultWithOkBrand<i32>, _, _, _, _>(|x: i32, y: i32| x + y, Ok(1), Err(2)),
728	///     Ok(1)
729	/// );
730	/// assert_eq!(
731	///     lift2::<ResultWithOkBrand<i32>, _, _, _, _>(|x: i32, y: i32| x + y, Ok(1), Ok(2)),
732	///     Ok(1)
733	/// );
734	/// ```
735	fn lift2<'a, A, B, C, Func>(
736		func: Func,
737		fa: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
738		fb: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>),
739	) -> Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, C>)
740	where
741		Func: Fn(A, B) -> C + 'a,
742		A: Clone + 'a,
743		B: Clone + 'a,
744		C: 'a,
745	{
746		match (fa, fb) {
747			(Err(a), Err(b)) => Err(func(a, b)),
748			(Ok(t), _) => Ok(t),
749			(_, Ok(t)) => Ok(t),
750		}
751	}
752}
753
754impl<T: 'static> Pointed for ResultWithOkBrand<T> {
755	/// Wraps a value in a result (as error).
756	///
757	/// This method wraps a value in the `Err` variant of a `Result`.
758	///
759	/// ### Type Signature
760	///
761	#[hm_signature(Pointed)]
762	///
763	/// ### Type Parameters
764	///
765	#[doc_type_params("The lifetime of the value.", "The type of the value to wrap.")]
766	///
767	/// ### Parameters
768	///
769	#[doc_params("The value to wrap.")]
770	///
771	/// ### Returns
772	///
773	/// `Err(a)`.
774	///
775	/// ### Examples
776	///
777	/// ```
778	/// use fp_library::functions::*;
779	/// use fp_library::brands::ResultWithOkBrand;
780	///
781	/// assert_eq!(pure::<ResultWithOkBrand<()>, _>(5), Err(5));
782	/// ```
783	fn pure<'a, A: 'a>(a: A) -> Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>) {
784		Err(a)
785	}
786}
787
788impl<T: Clone + 'static> ApplyFirst for ResultWithOkBrand<T> {}
789impl<T: Clone + 'static> ApplySecond for ResultWithOkBrand<T> {}
790
791impl<T: Clone + 'static> Semiapplicative for ResultWithOkBrand<T> {
792	/// Applies a wrapped function to a wrapped value (over error).
793	///
794	/// This method applies a function wrapped in a result (as error) to a value wrapped in a result (as error).
795	///
796	/// ### Type Signature
797	///
798	#[hm_signature(Semiapplicative)]
799	///
800	/// ### Type Parameters
801	///
802	#[doc_type_params(
803		"The lifetime of the values.",
804		"The brand of the cloneable function wrapper.",
805		"The type of the input value.",
806		"The type of the output value."
807	)]
808	///
809	/// ### Parameters
810	///
811	#[doc_params(
812		"The result containing the function (in Err).",
813		"The result containing the value (in Err)."
814	)]
815	///
816	/// ### Returns
817	///
818	/// `Err(f(a))` if both are `Err`, otherwise the first success encountered.
819	///
820	/// ### Examples
821	///
822	/// ```
823	/// use fp_library::{brands::*, classes::*, functions::*, Apply, Kind};
824	///
825	/// let f: Result<(), _> = Err(cloneable_fn_new::<RcFnBrand, _, _>(|x: i32| x * 2));
826	/// assert_eq!(apply::<RcFnBrand, ResultWithOkBrand<()>, _, _>(f, Err(5)), Err(10));
827	/// let f: Result<i32, _> = Err(cloneable_fn_new::<RcFnBrand, _, _>(|x: i32| x * 2));
828	/// assert_eq!(apply::<RcFnBrand, ResultWithOkBrand<i32>, _, _>(f, Ok(1)), Ok(1));
829	///
830	/// let f_ok: Result<i32, _> = Ok(1);
831	/// assert_eq!(apply::<RcFnBrand, ResultWithOkBrand<i32>, i32, i32>(f_ok, Err(5)), Ok(1));
832	/// ```
833	fn apply<'a, FnBrand: 'a + CloneableFn, A: 'a + Clone, B: 'a>(
834		ff: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, <FnBrand as CloneableFn>::Of<'a, A, B>>),
835		fa: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
836	) -> Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>) {
837		match (ff, fa) {
838			(Err(f), Err(a)) => Err(f(a)),
839			(Ok(t), _) => Ok(t),
840			(_, Ok(t)) => Ok(t),
841		}
842	}
843}
844
845impl<T: Clone + 'static> Semimonad for ResultWithOkBrand<T> {
846	/// Chains result computations (over error).
847	///
848	/// This method chains two computations, where the second computation depends on the result of the first (over error).
849	///
850	/// ### Type Signature
851	///
852	#[hm_signature(Semimonad)]
853	///
854	/// ### Type Parameters
855	///
856	#[doc_type_params(
857		"The lifetime of the values.",
858		"The type of the result of the first computation.",
859		"The type of the result of the second computation.",
860		"The type of the function to apply."
861	)]
862	///
863	/// ### Parameters
864	///
865	#[doc_params("The first result.", "The function to apply to the error value.")]
866	///
867	/// ### Returns
868	///
869	/// The result of applying `f` to the error if `ma` is `Err`, otherwise the original success.
870	///
871	/// ### Examples
872	///
873	/// ```
874	/// use fp_library::functions::*;
875	/// use fp_library::brands::ResultWithOkBrand;
876	///
877	/// assert_eq!(
878	///     bind::<ResultWithOkBrand<()>, _, _, _>(Err(5), |x| Err(x * 2)),
879	///     Err(10)
880	/// );
881	/// assert_eq!(
882	///     bind::<ResultWithOkBrand<i32>, _, _, _>(Err(5), |_| Ok::<_, i32>(1)),
883	///     Ok(1)
884	/// );
885	/// assert_eq!(
886	///     bind::<ResultWithOkBrand<i32>, _, _, _>(Ok(1), |x: i32| Err(x * 2)),
887	///     Ok(1)
888	/// );
889	/// ```
890	fn bind<'a, A: 'a, B: 'a, Func>(
891		ma: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
892		func: Func,
893	) -> Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>)
894	where
895		Func: Fn(A) -> Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>) + 'a,
896	{
897		match ma {
898			Ok(t) => Ok(t),
899			Err(e) => func(e),
900		}
901	}
902}
903
904impl<T: 'static> Foldable for ResultWithOkBrand<T> {
905	/// Folds the result from the right (over error).
906	///
907	/// This method performs a right-associative fold of the result (over error).
908	///
909	/// ### Type Signature
910	///
911	#[hm_signature(Foldable)]
912	///
913	/// ### Type Parameters
914	///
915	#[doc_type_params(
916		"The lifetime of the values.",
917		"The brand of the cloneable function to use.",
918		"The type of the elements in the structure.",
919		"The type of the accumulator.",
920		"The type of the folding function."
921	)]
922	///
923	/// ### Parameters
924	///
925	#[doc_params("The folding function.", "The initial value.", "The result to fold.")]
926	///
927	/// ### Returns
928	///
929	/// `func(a, initial)` if `fa` is `Err(a)`, otherwise `initial`.
930	///
931	/// ### Examples
932	///
933	/// ```
934	/// use fp_library::{brands::*, functions::*};
935	///
936	/// assert_eq!(fold_right::<RcFnBrand, ResultWithOkBrand<i32>, _, _, _>(|x: i32, acc| x + acc, 0, Err(1)), 1);
937	/// assert_eq!(fold_right::<RcFnBrand, ResultWithOkBrand<()>, _, _, _>(|x: i32, acc| x + acc, 0, Ok(())), 0);
938	/// ```
939	fn fold_right<'a, FnBrand, A: 'a, B: 'a, F>(
940		func: F,
941		initial: B,
942		fa: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
943	) -> B
944	where
945		F: Fn(A, B) -> B + 'a,
946		FnBrand: CloneableFn + 'a,
947	{
948		match fa {
949			Err(e) => func(e, initial),
950			Ok(_) => initial,
951		}
952	}
953
954	/// Folds the result from the left (over error).
955	///
956	/// This method performs a left-associative fold of the result (over error).
957	///
958	/// ### Type Signature
959	///
960	#[hm_signature(Foldable)]
961	///
962	/// ### Type Parameters
963	///
964	#[doc_type_params(
965		"The lifetime of the values.",
966		"The brand of the cloneable function to use.",
967		"The type of the elements in the structure.",
968		"The type of the accumulator.",
969		"The type of the folding function."
970	)]
971	///
972	/// ### Parameters
973	///
974	#[doc_params("The folding function.", "The initial value.", "The result to fold.")]
975	///
976	/// ### Returns
977	///
978	/// `func(initial, a)` if `fa` is `Err(a)`, otherwise `initial`.
979	///
980	/// ### Examples
981	///
982	/// ```
983	/// use fp_library::{brands::*, functions::*};
984	///
985	/// assert_eq!(fold_left::<RcFnBrand, ResultWithOkBrand<()>, _, _, _>(|acc, x: i32| acc + x, 0, Err(5)), 5);
986	/// assert_eq!(fold_left::<RcFnBrand, ResultWithOkBrand<i32>, _, _, _>(|acc, x: i32| acc + x, 0, Ok(1)), 0);
987	/// ```
988	fn fold_left<'a, FnBrand, A: 'a, B: 'a, F>(
989		func: F,
990		initial: B,
991		fa: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
992	) -> B
993	where
994		F: Fn(B, A) -> B + 'a,
995		FnBrand: CloneableFn + 'a,
996	{
997		match fa {
998			Err(e) => func(initial, e),
999			Ok(_) => initial,
1000		}
1001	}
1002
1003	/// Maps the value to a monoid and returns it (over error).
1004	///
1005	/// This method maps the element of the result to a monoid and then returns it (over error).
1006	///
1007	/// ### Type Signature
1008	///
1009	#[hm_signature(Foldable)]
1010	///
1011	/// ### Type Parameters
1012	///
1013	#[doc_type_params(
1014		"The lifetime of the values.",
1015		"The brand of the cloneable function to use.",
1016		"The type of the elements in the structure.",
1017		"The type of the monoid.",
1018		"The type of the mapping function."
1019	)]
1020	///
1021	/// ### Parameters
1022	///
1023	#[doc_params("The mapping function.", "The result to fold.")]
1024	///
1025	/// ### Returns
1026	///
1027	/// `func(a)` if `fa` is `Err(a)`, otherwise `M::empty()`.
1028	///
1029	/// ### Examples
1030	///
1031	/// ```
1032	/// use fp_library::{brands::*, functions::*};
1033	///
1034	/// assert_eq!(
1035	///     fold_map::<RcFnBrand, ResultWithOkBrand<()>, _, _, _>(|x: i32| x.to_string(), Err(5)),
1036	///     "5".to_string()
1037	/// );
1038	/// assert_eq!(
1039	///     fold_map::<RcFnBrand, ResultWithOkBrand<i32>, _, _, _>(|x: i32| x.to_string(), Ok(1)),
1040	///     "".to_string()
1041	/// );
1042	/// ```
1043	fn fold_map<'a, FnBrand, A: 'a, M, Func>(
1044		func: Func,
1045		fa: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
1046	) -> M
1047	where
1048		M: Monoid + 'a,
1049		Func: Fn(A) -> M + 'a,
1050		FnBrand: CloneableFn + 'a,
1051	{
1052		match fa {
1053			Err(e) => func(e),
1054			Ok(_) => M::empty(),
1055		}
1056	}
1057}
1058
1059impl<T: Clone + 'static> Traversable for ResultWithOkBrand<T> {
1060	/// Traverses the result with an applicative function (over error).
1061	///
1062	/// This method maps the element of the result to a computation, evaluates it, and combines the result into an applicative context (over error).
1063	///
1064	/// ### Type Signature
1065	///
1066	#[hm_signature(Traversable)]
1067	///
1068	/// ### Type Parameters
1069	///
1070	#[doc_type_params(
1071		"The lifetime of the values.",
1072		"The type of the elements in the traversable structure.",
1073		"The type of the elements in the resulting traversable structure.",
1074		"The applicative context.",
1075		"The type of the function to apply."
1076	)]
1077	///
1078	/// ### Parameters
1079	///
1080	#[doc_params("The function to apply.", "The result to traverse.")]
1081	///
1082	/// ### Returns
1083	///
1084	/// The result wrapped in the applicative context.
1085	///
1086	/// ### Examples
1087	///
1088	/// ```
1089	/// use fp_library::functions::*;
1090	/// use fp_library::brands::{ResultWithOkBrand, OptionBrand};
1091	///
1092	/// assert_eq!(
1093	///     traverse::<ResultWithOkBrand<()>, _, _, OptionBrand, _>(|x| Some(x * 2), Err(5)),
1094	///     Some(Err(10))
1095	/// );
1096	/// assert_eq!(
1097	///     traverse::<ResultWithOkBrand<i32>, _, _, OptionBrand, _>(|x: i32| Some(x * 2), Ok(1)),
1098	///     Some(Ok(1))
1099	/// );
1100	/// assert_eq!(
1101	///     traverse::<ResultWithOkBrand<()>, _, _, OptionBrand, _>(|_| None::<i32>, Err(5)),
1102	///     None
1103	/// );
1104	/// ```
1105	fn traverse<'a, A: 'a + Clone, B: 'a + Clone, F: Applicative, Func>(
1106		func: Func,
1107		ta: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
1108	) -> 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>)>)
1109	where
1110		Func: Fn(A) -> Apply!(<F as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>) + 'a,
1111		Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>): Clone,
1112	{
1113		match ta {
1114			Err(e) => F::map(|b| Err(b), func(e)),
1115			Ok(t) => F::pure(Ok(t)),
1116		}
1117	}
1118
1119	/// Sequences a result of applicative (over error).
1120	///
1121	/// This method evaluates the computation inside the result and accumulates the result into an applicative context (over error).
1122	///
1123	/// ### Type Signature
1124	///
1125	#[hm_signature(Traversable)]
1126	///
1127	/// ### Type Parameters
1128	///
1129	#[doc_type_params(
1130		"The lifetime of the values.",
1131		"The type of the elements in the traversable structure.",
1132		"The applicative context."
1133	)]
1134	///
1135	/// ### Parameters
1136	///
1137	#[doc_params("The result containing the applicative value.")]
1138	///
1139	/// ### Returns
1140	///
1141	/// The result wrapped in the applicative context.
1142	///
1143	/// ### Examples
1144	///
1145	/// ```
1146	/// use fp_library::functions::*;
1147	/// use fp_library::brands::{ResultWithOkBrand, OptionBrand};
1148	///
1149	/// assert_eq!(
1150	///     sequence::<ResultWithOkBrand<()>, _, OptionBrand>(Err(Some(5))),
1151	///     Some(Err(5))
1152	/// );
1153	/// assert_eq!(
1154	///     sequence::<ResultWithOkBrand<i32>, i32, OptionBrand>(Ok::<_, Option<i32>>(1)),
1155	///     Some(Ok::<i32, i32>(1))
1156	/// );
1157	/// assert_eq!(
1158	///     sequence::<ResultWithOkBrand<()>, _, OptionBrand>(Err(None::<i32>)),
1159	///     None
1160	/// );
1161	/// ```
1162	fn sequence<'a, A: 'a + Clone, F: Applicative>(
1163		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>)>)
1164	) -> 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>)>)
1165	where
1166		Apply!(<F as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>): Clone,
1167		Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>): Clone,
1168	{
1169		match ta {
1170			Err(fe) => F::map(|e| Err(e), fe),
1171			Ok(t) => F::pure(Ok(t)),
1172		}
1173	}
1174}
1175
1176impl<E: 'static> ParFoldable for ResultWithErrBrand<E> {
1177	/// Maps the value to a monoid and returns it, or returns empty, in parallel.
1178	///
1179	/// This method maps the element of the result to a monoid and then returns it. The mapping operation may be executed in parallel.
1180	///
1181	/// ### Type Signature
1182	///
1183	#[hm_signature(ParFoldable)]
1184	///
1185	/// ### Type Parameters
1186	///
1187	#[doc_type_params(
1188		"The lifetime of the values.",
1189		"The brand of the cloneable function wrapper.",
1190		"The element type.",
1191		"The monoid type."
1192	)]
1193	///
1194	/// ### Parameters
1195	///
1196	#[doc_params(
1197		"The thread-safe function to map each element to a monoid.",
1198		"The result to fold."
1199	)]
1200	///
1201	/// ### Returns
1202	///
1203	/// The combined monoid value.
1204	///
1205	/// ### Examples
1206	///
1207	/// ```
1208	/// use fp_library::{brands::*, classes::*, functions::*, types::*};
1209	///
1210	/// let x: Result<i32, ()> = Ok(5);
1211	/// let f = send_cloneable_fn_new::<ArcFnBrand, _, _>(|x: i32| x.to_string());
1212	/// assert_eq!(par_fold_map::<ArcFnBrand, ResultWithErrBrand<()>, _, _>(f.clone(), x), "5".to_string());
1213	///
1214	/// let x_err: Result<i32, i32> = Err(1);
1215	/// assert_eq!(par_fold_map::<ArcFnBrand, ResultWithErrBrand<i32>, _, _>(f, x_err), "".to_string());
1216	/// ```
1217	fn par_fold_map<'a, FnBrand, A, M>(
1218		func: <FnBrand as SendCloneableFn>::SendOf<'a, A, M>,
1219		fa: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
1220	) -> M
1221	where
1222		FnBrand: 'a + SendCloneableFn,
1223		A: 'a + Clone + Send + Sync,
1224		M: Monoid + Send + Sync + 'a,
1225	{
1226		match fa {
1227			Ok(a) => func(a),
1228			Err(_) => M::empty(),
1229		}
1230	}
1231
1232	/// Folds the result from the right in parallel.
1233	///
1234	/// This method folds the result by applying a function from right to left, potentially in parallel.
1235	///
1236	/// ### Type Signature
1237	///
1238	#[hm_signature(ParFoldable)]
1239	///
1240	/// ### Type Parameters
1241	///
1242	#[doc_type_params(
1243		"The lifetime of the values.",
1244		"The brand of the cloneable function wrapper.",
1245		"The element type.",
1246		"The accumulator type."
1247	)]
1248	///
1249	/// ### Parameters
1250	///
1251	#[doc_params(
1252		"The thread-safe function to apply to each element and the accumulator.",
1253		"The initial value.",
1254		"The result to fold."
1255	)]
1256	///
1257	/// ### Returns
1258	///
1259	/// The final accumulator value.
1260	///
1261	/// ### Examples
1262	///
1263	/// ```
1264	/// use fp_library::{brands::*, classes::*, functions::*};
1265	///
1266	/// let x: Result<i32, ()> = Ok(5);
1267	/// let f = send_cloneable_fn_new::<ArcFnBrand, _, _>(|(a, b): (i32, i32)| a + b);
1268	/// assert_eq!(par_fold_right::<ArcFnBrand, ResultWithErrBrand<()>, _, _>(f.clone(), 10, x), 15);
1269	///
1270	/// let x_err: Result<i32, i32> = Err(1);
1271	/// assert_eq!(par_fold_right::<ArcFnBrand, ResultWithErrBrand<i32>, _, _>(f, 10, x_err), 10);
1272	/// ```
1273	fn par_fold_right<'a, FnBrand, A, B>(
1274		func: <FnBrand as SendCloneableFn>::SendOf<'a, (A, B), B>,
1275		initial: B,
1276		fa: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
1277	) -> B
1278	where
1279		FnBrand: 'a + SendCloneableFn,
1280		A: 'a + Clone + Send + Sync,
1281		B: Send + Sync + 'a,
1282	{
1283		match fa {
1284			Ok(a) => func((a, initial)),
1285			Err(_) => initial,
1286		}
1287	}
1288}
1289
1290impl<T: 'static> ParFoldable for ResultWithOkBrand<T> {
1291	/// Maps the value to a monoid and returns it, or returns empty, in parallel (over error).
1292	///
1293	/// This method maps the element of the result to a monoid and then returns it (over error). The mapping operation may be executed in parallel.
1294	///
1295	/// ### Type Signature
1296	///
1297	#[hm_signature(ParFoldable)]
1298	///
1299	/// ### Type Parameters
1300	///
1301	#[doc_type_params(
1302		"The lifetime of the values.",
1303		"The brand of the cloneable function wrapper.",
1304		"The element type.",
1305		"The monoid type."
1306	)]
1307	///
1308	/// ### Parameters
1309	///
1310	#[doc_params(
1311		"The thread-safe function to map each element to a monoid.",
1312		"The result to fold."
1313	)]
1314	///
1315	/// ### Returns
1316	///
1317	/// The combined monoid value.
1318	///
1319	/// ### Examples
1320	///
1321	/// ```
1322	/// use fp_library::{brands::*, classes::*, functions::*, types::*};
1323	///
1324	/// let x: Result<(), i32> = Err(5);
1325	/// let f = send_cloneable_fn_new::<ArcFnBrand, _, _>(|x: i32| x.to_string());
1326	/// assert_eq!(par_fold_map::<ArcFnBrand, ResultWithOkBrand<()>, _, _>(f.clone(), x), "5".to_string());
1327	///
1328	/// let x_ok: Result<i32, i32> = Ok(1);
1329	/// assert_eq!(par_fold_map::<ArcFnBrand, ResultWithOkBrand<i32>, _, _>(f, x_ok), "".to_string());
1330	/// ```
1331	fn par_fold_map<'a, FnBrand, A, M>(
1332		func: <FnBrand as SendCloneableFn>::SendOf<'a, A, M>,
1333		fa: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
1334	) -> M
1335	where
1336		FnBrand: 'a + SendCloneableFn,
1337		A: 'a + Clone + Send + Sync,
1338		M: Monoid + Send + Sync + 'a,
1339	{
1340		match fa {
1341			Err(e) => func(e),
1342			Ok(_) => M::empty(),
1343		}
1344	}
1345
1346	/// Folds the result from the right in parallel (over error).
1347	///
1348	/// This method folds the result by applying a function from right to left, potentially in parallel (over error).
1349	///
1350	/// ### Type Signature
1351	///
1352	#[hm_signature(ParFoldable)]
1353	///
1354	/// ### Type Parameters
1355	///
1356	#[doc_type_params(
1357		"The lifetime of the values.",
1358		"The brand of the cloneable function wrapper.",
1359		"The element type.",
1360		"The accumulator type."
1361	)]
1362	///
1363	/// ### Parameters
1364	///
1365	#[doc_params(
1366		"The thread-safe function to apply to each element and the accumulator.",
1367		"The initial value.",
1368		"The result to fold."
1369	)]
1370	///
1371	/// ### Returns
1372	///
1373	/// The final accumulator value.
1374	///
1375	/// ### Examples
1376	///
1377	/// ```
1378	/// use fp_library::{brands::*, classes::*, functions::*};
1379	///
1380	/// let x: Result<(), i32> = Err(5);
1381	/// let f = send_cloneable_fn_new::<ArcFnBrand, _, _>(|(a, b): (i32, i32)| a + b);
1382	/// assert_eq!(par_fold_right::<ArcFnBrand, ResultWithOkBrand<()>, _, _>(f.clone(), 10, x), 15);
1383	///
1384	/// let x_ok: Result<i32, i32> = Ok(1);
1385	/// assert_eq!(par_fold_right::<ArcFnBrand, ResultWithOkBrand<i32>, _, _>(f, 10, x_ok), 10);
1386	/// ```
1387	fn par_fold_right<'a, FnBrand, A, B>(
1388		func: <FnBrand as SendCloneableFn>::SendOf<'a, (A, B), B>,
1389		initial: B,
1390		fa: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
1391	) -> B
1392	where
1393		FnBrand: 'a + SendCloneableFn,
1394		A: 'a + Clone + Send + Sync,
1395		B: Send + Sync + 'a,
1396	{
1397		match fa {
1398			Err(e) => func((e, initial)),
1399			Ok(_) => initial,
1400		}
1401	}
1402}
1403
1404#[cfg(test)]
1405mod tests {
1406	use super::*;
1407	use crate::{brands::*, classes::bifunctor::*, functions::*};
1408	use quickcheck_macros::quickcheck;
1409
1410	// Bifunctor Tests
1411
1412	/// Tests `bimap` on `Ok` and `Err`.
1413	#[test]
1414	fn test_bimap() {
1415		let x: Result<i32, i32> = Ok(5);
1416		assert_eq!(bimap::<ResultBrand, _, _, _, _, _, _>(|e| e + 1, |s| s * 2, x), Ok(10));
1417
1418		let y: Result<i32, i32> = Err(5);
1419		assert_eq!(bimap::<ResultBrand, _, _, _, _, _, _>(|e| e + 1, |s| s * 2, y), Err(6));
1420	}
1421
1422	// Bifunctor Laws
1423
1424	/// Tests the identity law for Bifunctor.
1425	#[quickcheck]
1426	fn bifunctor_identity(x: Result<i32, i32>) -> bool {
1427		bimap::<ResultBrand, _, _, _, _, _, _>(identity, identity, x) == x
1428	}
1429
1430	/// Tests the composition law for Bifunctor.
1431	#[quickcheck]
1432	fn bifunctor_composition(x: Result<i32, i32>) -> bool {
1433		let f = |x: i32| x.wrapping_add(1);
1434		let g = |x: i32| x.wrapping_mul(2);
1435		let h = |x: i32| x.wrapping_sub(1);
1436		let i = |x: i32| if x == 0 { 0 } else { x.wrapping_div(2) };
1437
1438		bimap::<ResultBrand, _, _, _, _, _, _>(compose(f, g), compose(h, i), x)
1439			== bimap::<ResultBrand, _, _, _, _, _, _>(
1440				f,
1441				h,
1442				bimap::<ResultBrand, _, _, _, _, _, _>(g, i, x),
1443			)
1444	}
1445
1446	// Functor Laws
1447
1448	/// Tests the identity law for Functor.
1449	#[quickcheck]
1450	fn functor_identity(x: Result<i32, i32>) -> bool {
1451		map::<ResultWithErrBrand<i32>, _, _, _>(identity, x) == x
1452	}
1453
1454	/// Tests the composition law for Functor.
1455	#[quickcheck]
1456	fn functor_composition(x: Result<i32, i32>) -> bool {
1457		let f = |x: i32| x.wrapping_add(1);
1458		let g = |x: i32| x.wrapping_mul(2);
1459		map::<ResultWithErrBrand<i32>, _, _, _>(compose(f, g), x)
1460			== map::<ResultWithErrBrand<i32>, _, _, _>(
1461				f,
1462				map::<ResultWithErrBrand<i32>, _, _, _>(g, x),
1463			)
1464	}
1465
1466	// Applicative Laws
1467
1468	/// Tests the identity law for Applicative.
1469	#[quickcheck]
1470	fn applicative_identity(v: Result<i32, i32>) -> bool {
1471		apply::<RcFnBrand, ResultWithErrBrand<i32>, _, _>(
1472			pure::<ResultWithErrBrand<i32>, _>(<RcFnBrand as CloneableFn>::new(identity)),
1473			v,
1474		) == v
1475	}
1476
1477	/// Tests the homomorphism law for Applicative.
1478	#[quickcheck]
1479	fn applicative_homomorphism(x: i32) -> bool {
1480		let f = |x: i32| x.wrapping_mul(2);
1481		apply::<RcFnBrand, ResultWithErrBrand<i32>, _, _>(
1482			pure::<ResultWithErrBrand<i32>, _>(<RcFnBrand as CloneableFn>::new(f)),
1483			pure::<ResultWithErrBrand<i32>, _>(x),
1484		) == pure::<ResultWithErrBrand<i32>, _>(f(x))
1485	}
1486
1487	/// Tests the composition law for Applicative.
1488	#[quickcheck]
1489	fn applicative_composition(
1490		w: Result<i32, i32>,
1491		u_is_ok: bool,
1492		v_is_ok: bool,
1493	) -> bool {
1494		let v_fn = |x: i32| x.wrapping_mul(2);
1495		let u_fn = |x: i32| x.wrapping_add(1);
1496
1497		let v = if v_is_ok {
1498			pure::<ResultWithErrBrand<i32>, _>(<RcFnBrand as CloneableFn>::new(v_fn))
1499		} else {
1500			Err(100)
1501		};
1502		let u = if u_is_ok {
1503			pure::<ResultWithErrBrand<i32>, _>(<RcFnBrand as CloneableFn>::new(u_fn))
1504		} else {
1505			Err(200)
1506		};
1507
1508		// RHS: u <*> (v <*> w)
1509		let vw = apply::<RcFnBrand, ResultWithErrBrand<i32>, _, _>(v.clone(), w.clone());
1510		let rhs = apply::<RcFnBrand, ResultWithErrBrand<i32>, _, _>(u.clone(), vw);
1511
1512		// LHS: pure(compose) <*> u <*> v <*> w
1513		// equivalent to (u . v) <*> w
1514		let uv = match (u, v) {
1515			(Ok(uf), Ok(vf)) => {
1516				let composed = move |x| uf(vf(x));
1517				Ok(<RcFnBrand as CloneableFn>::new(composed))
1518			}
1519			(Err(e), _) => Err(e),
1520			(_, Err(e)) => Err(e),
1521		};
1522
1523		let lhs = apply::<RcFnBrand, ResultWithErrBrand<i32>, _, _>(uv, w);
1524
1525		lhs == rhs
1526	}
1527
1528	/// Tests the interchange law for Applicative.
1529	#[quickcheck]
1530	fn applicative_interchange(y: i32) -> bool {
1531		// u <*> pure y = pure ($ y) <*> u
1532		let f = |x: i32| x.wrapping_mul(2);
1533		let u = pure::<ResultWithErrBrand<i32>, _>(<RcFnBrand as CloneableFn>::new(f));
1534
1535		let lhs = apply::<RcFnBrand, ResultWithErrBrand<i32>, _, _>(
1536			u.clone(),
1537			pure::<ResultWithErrBrand<i32>, _>(y),
1538		);
1539
1540		let rhs_fn =
1541			<RcFnBrand as CloneableFn>::new(move |f: std::rc::Rc<dyn Fn(i32) -> i32>| f(y));
1542		let rhs = apply::<RcFnBrand, ResultWithErrBrand<i32>, _, _>(
1543			pure::<ResultWithErrBrand<i32>, _>(rhs_fn),
1544			u,
1545		);
1546
1547		lhs == rhs
1548	}
1549
1550	// Monad Laws
1551
1552	/// Tests the left identity law for Monad.
1553	#[quickcheck]
1554	fn monad_left_identity(a: i32) -> bool {
1555		let f = |x: i32| -> Result<i32, i32> { Err(x.wrapping_mul(2)) };
1556		bind::<ResultWithErrBrand<i32>, _, _, _>(pure::<ResultWithErrBrand<i32>, _>(a), f) == f(a)
1557	}
1558
1559	/// Tests the right identity law for Monad.
1560	#[quickcheck]
1561	fn monad_right_identity(m: Result<i32, i32>) -> bool {
1562		bind::<ResultWithErrBrand<i32>, _, _, _>(m, pure::<ResultWithErrBrand<i32>, _>) == m
1563	}
1564
1565	/// Tests the associativity law for Monad.
1566	#[quickcheck]
1567	fn monad_associativity(m: Result<i32, i32>) -> bool {
1568		let f = |x: i32| -> Result<i32, i32> { Err(x.wrapping_mul(2)) };
1569		let g = |x: i32| -> Result<i32, i32> { Err(x.wrapping_add(1)) };
1570		bind::<ResultWithErrBrand<i32>, _, _, _>(bind::<ResultWithErrBrand<i32>, _, _, _>(m, f), g)
1571			== bind::<ResultWithErrBrand<i32>, _, _, _>(m, |x| {
1572				bind::<ResultWithErrBrand<i32>, _, _, _>(f(x), g)
1573			})
1574	}
1575
1576	// Edge Cases
1577
1578	/// Tests `map` on `Err`.
1579	#[test]
1580	fn map_err() {
1581		assert_eq!(
1582			map::<ResultWithErrBrand<i32>, _, _, _>(|x: i32| x + 1, Err::<i32, i32>(1)),
1583			Err(1)
1584		);
1585	}
1586
1587	/// Tests `bind` on `Err`.
1588	#[test]
1589	fn bind_err() {
1590		assert_eq!(
1591			bind::<ResultWithErrBrand<i32>, _, _, _>(Err::<i32, i32>(1), |x: i32| Ok(x + 1)),
1592			Err(1)
1593		);
1594	}
1595
1596	/// Tests `bind` returning `Err`.
1597	#[test]
1598	fn bind_returning_err() {
1599		assert_eq!(bind::<ResultWithErrBrand<i32>, _, _, _>(Ok(1), |_| Err::<i32, i32>(2)), Err(2));
1600	}
1601
1602	/// Tests `fold_right` on `Err`.
1603	#[test]
1604	fn fold_right_err() {
1605		assert_eq!(
1606			crate::classes::foldable::fold_right::<RcFnBrand, ResultWithErrBrand<i32>, _, _, _>(
1607				|x: i32, acc| x + acc,
1608				0,
1609				Err(1)
1610			),
1611			0
1612		);
1613	}
1614
1615	/// Tests `fold_left` on `Err`.
1616	#[test]
1617	fn fold_left_err() {
1618		assert_eq!(
1619			crate::classes::foldable::fold_left::<RcFnBrand, ResultWithErrBrand<i32>, _, _, _>(
1620				|acc, x: i32| acc + x,
1621				0,
1622				Err(1)
1623			),
1624			0
1625		);
1626	}
1627
1628	/// Tests `traverse` on `Err`.
1629	#[test]
1630	fn traverse_err() {
1631		assert_eq!(
1632			crate::classes::traversable::traverse::<ResultWithErrBrand<i32>, _, _, OptionBrand, _>(
1633				|x: i32| Some(x + 1),
1634				Err(1)
1635			),
1636			Some(Err(1))
1637		);
1638	}
1639
1640	/// Tests `traverse` returning `Err`.
1641	#[test]
1642	fn traverse_returning_err() {
1643		assert_eq!(
1644			crate::classes::traversable::traverse::<ResultWithErrBrand<i32>, _, _, OptionBrand, _>(
1645				|_: i32| None::<i32>,
1646				Ok(1)
1647			),
1648			None
1649		);
1650	}
1651
1652	// ParFoldable Tests for ResultWithErrBrand
1653
1654	/// Tests `par_fold_map` on `Ok`.
1655	#[test]
1656	fn par_fold_map_ok() {
1657		let x: Result<i32, ()> = Ok(5);
1658		let f = send_cloneable_fn_new::<ArcFnBrand, _, _>(|x: i32| x.to_string());
1659		assert_eq!(par_fold_map::<ArcFnBrand, ResultWithErrBrand<()>, _, _>(f, x), "5".to_string());
1660	}
1661
1662	/// Tests `par_fold_map` on `Err`.
1663	#[test]
1664	fn par_fold_map_err_val() {
1665		let x: Result<i32, i32> = Err(5);
1666		let f = send_cloneable_fn_new::<ArcFnBrand, _, _>(|x: i32| x.to_string());
1667		assert_eq!(par_fold_map::<ArcFnBrand, ResultWithErrBrand<i32>, _, _>(f, x), "".to_string());
1668	}
1669
1670	/// Tests `par_fold_right` on `Ok`.
1671	#[test]
1672	fn par_fold_right_ok() {
1673		let x: Result<i32, ()> = Ok(5);
1674		let f = send_cloneable_fn_new::<ArcFnBrand, _, _>(|(a, b): (i32, i32)| a + b);
1675		assert_eq!(par_fold_right::<ArcFnBrand, ResultWithErrBrand<()>, _, _>(f, 10, x), 15);
1676	}
1677
1678	/// Tests `par_fold_right` on `Err`.
1679	#[test]
1680	fn par_fold_right_err_val() {
1681		let x: Result<i32, i32> = Err(5);
1682		let f = send_cloneable_fn_new::<ArcFnBrand, _, _>(|(a, b): (i32, i32)| a + b);
1683		assert_eq!(par_fold_right::<ArcFnBrand, ResultWithErrBrand<i32>, _, _>(f, 10, x), 10);
1684	}
1685
1686	// ParFoldable Tests for ResultWithOkBrand
1687
1688	/// Tests `par_fold_map` on `Err` (which holds the value for ResultWithOkBrand).
1689	#[test]
1690	fn par_fold_map_err_ok_brand() {
1691		let x: Result<(), i32> = Err(5);
1692		let f = send_cloneable_fn_new::<ArcFnBrand, _, _>(|x: i32| x.to_string());
1693		assert_eq!(
1694			par_fold_map::<ArcFnBrand, ResultWithOkBrand<()>, _, _>(f.clone(), x),
1695			"5".to_string()
1696		);
1697	}
1698
1699	/// Tests `par_fold_map` on `Ok` (which is empty for ResultWithOkBrand).
1700	#[test]
1701	fn par_fold_map_ok_ok_brand() {
1702		let x: Result<i32, i32> = Ok(5);
1703		let f = send_cloneable_fn_new::<ArcFnBrand, _, _>(|x: i32| x.to_string());
1704		assert_eq!(par_fold_map::<ArcFnBrand, ResultWithOkBrand<i32>, _, _>(f, x), "".to_string());
1705	}
1706
1707	/// Tests `par_fold_right` on `Err` (which holds the value for ResultWithOkBrand).
1708	#[test]
1709	fn par_fold_right_err_ok_brand() {
1710		let x: Result<(), i32> = Err(5);
1711		let f = send_cloneable_fn_new::<ArcFnBrand, _, _>(|(a, b): (i32, i32)| a + b);
1712		assert_eq!(par_fold_right::<ArcFnBrand, ResultWithOkBrand<()>, _, _>(f.clone(), 10, x), 15);
1713	}
1714
1715	/// Tests `par_fold_right` on `Ok` (which is empty for ResultWithOkBrand).
1716	#[test]
1717	fn par_fold_right_ok_ok_brand() {
1718		let x: Result<i32, i32> = Ok(5);
1719		let f = send_cloneable_fn_new::<ArcFnBrand, _, _>(|(a, b): (i32, i32)| a + b);
1720		assert_eq!(par_fold_right::<ArcFnBrand, ResultWithOkBrand<i32>, _, _>(f, 10, x), 10);
1721	}
1722}