1#[fp_macros::document_module]
6mod inner {
7 use {
8 crate::{
9 Apply,
10 brands::{
11 OptionBrand,
12 VecBrand,
13 },
14 classes::*,
15 dispatch::Ref,
16 impl_kind,
17 kinds::*,
18 },
19 core::ops::ControlFlow,
20 fp_macros::*,
21 };
22
23 impl_kind! {
24 for VecBrand {
25 type Of<'a, A: 'a>: 'a = Vec<A>;
26 }
27 }
28
29 impl VecBrand {
30 #[document_signature]
34 #[document_type_parameters("The type of the elements in the vector.")]
36 #[document_parameters(
38 "A value to prepend to the vector.",
39 "A vector to prepend the value to."
40 )]
41 #[document_returns(
43 "A new vector consisting of the `head` element prepended to the `tail` vector."
44 )]
45 #[document_examples]
46 pub fn construct<A>(
60 head: A,
61 tail: Vec<A>,
62 ) -> Vec<A>
63 where
64 A: Clone, {
65 [vec![head], tail].concat()
66 }
67
68 #[document_signature]
72 #[document_type_parameters("The type of the elements in the vector.")]
74 #[document_parameters("The vector slice to deconstruct.")]
76 #[document_returns(
78 "An [`Option`] containing a tuple of the head element and the remaining tail vector, or [`None`] if the slice is empty."
79 )]
80 #[document_examples]
82 pub fn deconstruct<A>(slice: &[A]) -> Option<(A, Vec<A>)>
94 where
95 A: Clone, {
96 match slice {
97 [] => None,
98 [head, tail @ ..] => Some((head.clone(), tail.to_vec())),
99 }
100 }
101 }
102
103 impl Functor for VecBrand {
104 #[document_signature]
108 #[document_type_parameters(
110 "The lifetime of the elements.",
111 "The type of the elements in the vector.",
112 "The type of the elements in the resulting vector."
113 )]
114 #[document_parameters("The function to apply to each element.", "The vector to map over.")]
116 #[document_returns("A new vector containing the results of applying the function.")]
118 #[document_examples]
120 fn map<'a, A: 'a, B: 'a>(
130 func: impl Fn(A) -> B + 'a,
131 fa: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
132 ) -> Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>) {
133 fa.into_iter().map(func).collect()
134 }
135 }
136
137 impl Lift for VecBrand {
138 #[document_signature]
142 #[document_type_parameters(
144 "The lifetime of the elements.",
145 "The type of the elements in the first vector.",
146 "The type of the elements in the second vector.",
147 "The type of the elements in the resulting vector."
148 )]
149 #[document_parameters(
151 "The binary function to apply.",
152 "The first vector.",
153 "The second vector."
154 )]
155 #[document_returns(
157 "A new vector containing the results of applying the function to all pairs of elements."
158 )]
159 #[document_examples]
160 fn lift2<'a, A, B, C>(
173 func: impl Fn(A, B) -> C + 'a,
174 fa: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
175 fb: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>),
176 ) -> Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, C>)
177 where
178 A: Clone + 'a,
179 B: Clone + 'a,
180 C: 'a, {
181 fa.iter().flat_map(|a| fb.iter().map(|b| func(a.clone(), b.clone()))).collect()
182 }
183 }
184
185 impl Pointed for VecBrand {
186 #[document_signature]
190 #[document_type_parameters("The lifetime of the value.", "The type of the value to wrap.")]
192 #[document_parameters("The value to wrap.")]
194 #[document_returns("A vector containing the single value.")]
196 #[document_examples]
198 fn pure<'a, A: 'a>(a: A) -> Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>) {
208 vec![a]
209 }
210 }
211
212 impl ApplyFirst for VecBrand {}
213 impl ApplySecond for VecBrand {}
214
215 impl Semiapplicative for VecBrand {
216 #[document_signature]
220 #[document_type_parameters(
222 "The lifetime of the values.",
223 "The brand of the cloneable function wrapper.",
224 "The type of the input values.",
225 "The type of the output values."
226 )]
227 #[document_parameters(
229 "The vector containing the functions.",
230 "The vector containing the values."
231 )]
232 #[document_returns(
234 "A new vector containing the results of applying each function to each value."
235 )]
236 #[document_examples]
237 fn apply<'a, FnBrand: 'a + CloneFn, A: 'a + Clone, B: 'a>(
252 ff: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, <FnBrand as CloneFn>::Of<'a, A, B>>),
253 fa: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
254 ) -> Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>) {
255 ff.iter().flat_map(|f| fa.iter().map(move |a| f(a.clone()))).collect()
256 }
257 }
258
259 impl Semimonad for VecBrand {
260 #[document_signature]
264 #[document_type_parameters(
266 "The lifetime of the elements.",
267 "The type of the elements in the input vector.",
268 "The type of the elements in the output vector."
269 )]
270 #[document_parameters(
272 "The first vector.",
273 "The function to apply to each element, returning a vector."
274 )]
275 #[document_returns("A new vector containing the flattened results.")]
277 #[document_examples]
278 fn bind<'a, A: 'a, B: 'a>(
291 ma: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
292 func: impl Fn(A) -> Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>) + 'a,
293 ) -> Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>) {
294 ma.into_iter().flat_map(func).collect()
295 }
296 }
297
298 impl Alt for VecBrand {
299 #[document_signature]
304 #[document_type_parameters("The lifetime of the elements.", "The type of the elements.")]
306 #[document_parameters("The first vector.", "The second vector.")]
308 #[document_returns("The concatenated vector.")]
310 #[document_examples]
311 fn alt<'a, A: 'a>(
324 fa1: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
325 fa2: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
326 ) -> Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>) {
327 let mut result = fa1;
328 result.extend(fa2);
329 result
330 }
331 }
332
333 impl RefAlt for VecBrand {
334 #[document_signature]
340 #[document_type_parameters("The lifetime of the elements.", "The type of the elements.")]
342 #[document_parameters("The first vector.", "The second vector.")]
344 #[document_returns("A new vector containing cloned elements from both inputs.")]
346 #[document_examples]
347 fn ref_alt<'a, A: 'a + Clone>(
360 fa1: &Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
361 fa2: &Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
362 ) -> Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>) {
363 fa1.iter().chain(fa2.iter()).cloned().collect()
364 }
365 }
366
367 impl Plus for VecBrand {
368 #[document_signature]
370 #[document_type_parameters("The lifetime of the elements.", "The type of the elements.")]
372 #[document_returns("An empty vector.")]
374 #[document_examples]
375 fn empty<'a, A: 'a>() -> Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>) {
386 Vec::new()
387 }
388 }
389
390 impl Foldable for VecBrand {
391 #[document_signature]
395 #[document_type_parameters(
397 "The lifetime of the elements.",
398 "The brand of the cloneable function to use.",
399 "The type of the elements in the vector.",
400 "The type of the accumulator."
401 )]
402 #[document_parameters("The folding function.", "The initial value.", "The vector to fold.")]
404 #[document_returns("The final accumulator value.")]
406 #[document_examples]
408 fn fold_right<'a, FnBrand, A: 'a + Clone, B: 'a>(
425 func: impl Fn(A, B) -> B + 'a,
426 initial: B,
427 fa: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
428 ) -> B
429 where
430 FnBrand: CloneFn + 'a, {
431 fa.into_iter().rev().fold(initial, |acc, x| func(x, acc))
432 }
433
434 #[document_signature]
438 #[document_type_parameters(
440 "The lifetime of the elements.",
441 "The brand of the cloneable function to use.",
442 "The type of the elements in the vector.",
443 "The type of the accumulator."
444 )]
445 #[document_parameters(
447 "The function to apply to the accumulator and each element.",
448 "The initial value of the accumulator.",
449 "The vector to fold."
450 )]
451 #[document_returns("The final accumulator value.")]
453 #[document_examples]
454 fn fold_left<'a, FnBrand, A: 'a + Clone, B: 'a>(
471 func: impl Fn(B, A) -> B + 'a,
472 initial: B,
473 fa: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
474 ) -> B
475 where
476 FnBrand: CloneFn + 'a, {
477 fa.into_iter().fold(initial, func)
478 }
479
480 #[document_signature]
484 #[document_type_parameters(
486 "The lifetime of the elements.",
487 "The brand of the cloneable function to use.",
488 "The type of the elements in the vector.",
489 "The type of the monoid."
490 )]
491 #[document_parameters("The mapping function.", "The vector to fold.")]
493 #[document_returns("The combined monoid value.")]
495 #[document_examples]
497 fn fold_map<'a, FnBrand, A: 'a + Clone, M>(
513 func: impl Fn(A) -> M + 'a,
514 fa: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
515 ) -> M
516 where
517 M: Monoid + 'a,
518 FnBrand: CloneFn + 'a, {
519 fa.into_iter().map(func).fold(M::empty(), |acc, x| M::append(acc, x))
520 }
521 }
522
523 impl Traversable for VecBrand {
524 #[document_signature]
528 #[document_type_parameters(
530 "The lifetime of the elements.",
531 "The type of the elements in the traversable structure.",
532 "The type of the elements in the resulting traversable structure.",
533 "The applicative context."
534 )]
535 #[document_parameters(
537 "The function to apply to each element, returning a value in an applicative context.",
538 "The vector to traverse."
539 )]
540 #[document_returns("The vector wrapped in the applicative context.")]
542 #[document_examples]
543 fn traverse<'a, A: 'a + Clone, B: 'a + Clone, F: Applicative>(
559 func: impl Fn(A) -> Apply!(<F as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>) + 'a,
560 ta: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
561 ) -> 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>)>)
562 where
563 Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>): Clone,
564 Apply!(<F as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>): Clone, {
565 let len = ta.len();
566 ta.into_iter().fold(F::pure(Vec::with_capacity(len)), |acc, x| {
567 F::lift2(
568 |mut v, b| {
569 v.push(b);
570 v
571 },
572 acc,
573 func(x),
574 )
575 })
576 }
577
578 #[document_signature]
582 #[document_type_parameters(
584 "The lifetime of the elements.",
585 "The type of the elements in the traversable structure.",
586 "The applicative context."
587 )]
588 #[document_parameters("The vector containing the applicative values.")]
590 #[document_returns("The vector wrapped in the applicative context.")]
592 #[document_examples]
594 fn sequence<'a, A: 'a + Clone, F: Applicative>(
607 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>)>)
608 ) -> 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>)>)
609 where
610 Apply!(<F as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>): Clone,
611 Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>): Clone, {
612 let len = ta.len();
613 ta.into_iter().fold(F::pure(Vec::with_capacity(len)), |acc, x| {
614 F::lift2(
615 |mut v, a| {
616 v.push(a);
617 v
618 },
619 acc,
620 x,
621 )
622 })
623 }
624 }
625
626 impl WithIndex for VecBrand {
627 type Index = usize;
628 }
629
630 impl FunctorWithIndex for VecBrand {
631 #[document_signature]
633 #[document_type_parameters(
634 "The lifetime of the elements.",
635 "The type of the elements in the vector.",
636 "The type of the elements in the resulting vector."
637 )]
638 #[document_parameters(
639 "The function to apply to each element and its index.",
640 "The vector to map over."
641 )]
642 #[document_returns("A new vector containing the results of applying the function.")]
643 #[document_examples]
644 fn map_with_index<'a, A: 'a, B: 'a>(
658 f: impl Fn(usize, A) -> B + 'a,
659 fa: Vec<A>,
660 ) -> Vec<B> {
661 fa.into_iter().enumerate().map(|(i, a)| f(i, a)).collect()
662 }
663 }
664
665 impl FoldableWithIndex for VecBrand {
666 #[document_signature]
668 #[document_type_parameters(
669 "The lifetime of the elements.",
670 "The brand of the cloneable function to use.",
671 "The type of the elements in the vector.",
672 "The monoid type."
673 )]
674 #[document_parameters(
675 "The function to apply to each element and its index.",
676 "The vector to fold."
677 )]
678 #[document_returns("The combined monoid value.")]
679 #[document_examples]
680 fn fold_map_with_index<'a, FnBrand, A: 'a + Clone, R: Monoid + 'a>(
695 f: impl Fn(usize, A) -> R + 'a,
696 fa: Vec<A>,
697 ) -> R
698 where
699 FnBrand: LiftFn + 'a, {
700 fa.into_iter()
701 .enumerate()
702 .map(|(i, a)| f(i, a))
703 .fold(R::empty(), |acc, x| R::append(acc, x))
704 }
705 }
706
707 impl TraversableWithIndex for VecBrand {
708 #[document_signature]
710 #[document_type_parameters(
711 "The lifetime of the elements.",
712 "The type of the elements in the vector.",
713 "The type of the elements in the resulting vector.",
714 "The applicative context."
715 )]
716 #[document_parameters(
717 "The function to apply to each element and its index, returning a value in an applicative context.",
718 "The vector to traverse."
719 )]
720 #[document_returns("The vector wrapped in the applicative context.")]
721 #[document_examples]
722 fn traverse_with_index<'a, A: 'a, B: 'a + Clone, M: Applicative>(
740 f: impl Fn(usize, A) -> M::Of<'a, B> + 'a,
741 ta: Vec<A>,
742 ) -> M::Of<'a, Vec<B>> {
743 let len = ta.len();
744 ta.into_iter().enumerate().fold(M::pure(Vec::with_capacity(len)), |acc, (i, x)| {
745 M::lift2(
746 |mut v, b| {
747 v.push(b);
748 v
749 },
750 acc,
751 f(i, x),
752 )
753 })
754 }
755 }
756
757 #[document_type_parameters("The type of the elements in the vector.")]
758 impl<A: Clone> Semigroup for Vec<A> {
759 #[document_signature]
763 #[document_parameters("The first vector.", "The second vector.")]
765 #[document_returns("The concatenated vector.")]
767 #[document_examples]
769 fn append(
776 a: Self,
777 b: Self,
778 ) -> Self {
779 [a, b].concat()
780 }
781 }
782
783 #[document_type_parameters("The type of the elements in the vector.")]
784 impl<A: Clone> Monoid for Vec<A> {
785 #[document_signature]
789 #[document_returns("An empty vector.")]
791 #[document_examples]
793 fn empty() -> Self {
800 Vec::new()
801 }
802 }
803
804 impl VecBrand {
805 #[document_signature]
810 #[document_type_parameters(
812 "The lifetime of the elements.",
813 "The input element type.",
814 "The output element type."
815 )]
816 #[document_parameters(
818 "The function to apply to each element. Must be `Send + Sync`.",
819 "The vector to map over."
820 )]
821 #[document_returns("A new vector containing the mapped elements.")]
823 #[document_examples]
825 pub fn par_map<'a, A: 'a + Send, B: 'a + Send>(
833 f: impl Fn(A) -> B + Send + Sync + 'a,
834 fa: Vec<A>,
835 ) -> Vec<B> {
836 #[cfg(feature = "rayon")]
837 {
838 use rayon::prelude::*;
839 fa.into_par_iter().map(f).collect()
840 }
841 #[cfg(not(feature = "rayon"))]
842 fa.into_iter().map(f).collect()
843 }
844
845 #[document_signature]
850 #[document_type_parameters("The lifetime of the elements.", "The element type.")]
852 #[document_parameters("The vector of options.")]
854 #[document_returns("A new vector containing the unwrapped `Some` values.")]
856 #[document_examples]
858 pub fn par_compact<'a, A: 'a + Send>(fa: Vec<Option<A>>) -> Vec<A> {
866 #[cfg(feature = "rayon")]
867 {
868 use rayon::prelude::*;
869 fa.into_par_iter().flatten().collect()
870 }
871 #[cfg(not(feature = "rayon"))]
872 fa.into_iter().flatten().collect()
873 }
874
875 #[document_signature]
880 #[document_type_parameters(
882 "The lifetime of the elements.",
883 "The error type.",
884 "The success type."
885 )]
886 #[document_parameters("The vector of results.")]
888 #[document_returns(
890 "A pair `(errs, oks)` where `errs` contains the `Err` values and `oks` the `Ok` values."
891 )]
892 #[document_examples]
894 pub fn par_separate<'a, E: 'a + Send, O: 'a + Send>(
904 fa: Vec<Result<O, E>>
905 ) -> (Vec<E>, Vec<O>) {
906 #[cfg(feature = "rayon")]
907 {
908 use rayon::{
909 iter::Either,
910 prelude::*,
911 };
912 fa.into_par_iter().partition_map(|r| match r {
913 Ok(o) => Either::Right(o),
914 Err(e) => Either::Left(e),
915 })
916 }
917 #[cfg(not(feature = "rayon"))]
918 {
919 let mut errs = Vec::new();
920 let mut oks = Vec::new();
921 for result in fa {
922 match result {
923 Ok(o) => oks.push(o),
924 Err(e) => errs.push(e),
925 }
926 }
927 (errs, oks)
928 }
929 }
930
931 #[document_signature]
936 #[document_type_parameters(
938 "The lifetime of the elements.",
939 "The input element type.",
940 "The output element type."
941 )]
942 #[document_parameters(
944 "The function to apply. Must be `Send + Sync`.",
945 "The vector to filter and map."
946 )]
947 #[document_returns("A new vector containing the `Some` results of applying `f`.")]
949 #[document_examples]
951 pub fn par_filter_map<'a, A: 'a + Send, B: 'a + Send>(
962 f: impl Fn(A) -> Option<B> + Send + Sync + 'a,
963 fa: Vec<A>,
964 ) -> Vec<B> {
965 #[cfg(feature = "rayon")]
966 {
967 use rayon::prelude::*;
968 fa.into_par_iter().filter_map(f).collect()
969 }
970 #[cfg(not(feature = "rayon"))]
971 fa.into_iter().filter_map(f).collect()
972 }
973
974 #[document_signature]
979 #[document_type_parameters("The lifetime of the elements.", "The element type.")]
981 #[document_parameters("The predicate. Must be `Send + Sync`.", "The vector to filter.")]
983 #[document_returns("A new vector containing only the elements satisfying `f`.")]
985 #[document_examples]
987 pub fn par_filter<'a, A: 'a + Send>(
995 f: impl Fn(&A) -> bool + Send + Sync + 'a,
996 fa: Vec<A>,
997 ) -> Vec<A> {
998 #[cfg(feature = "rayon")]
999 {
1000 use rayon::prelude::*;
1001 fa.into_par_iter().filter(|a| f(a)).collect()
1002 }
1003 #[cfg(not(feature = "rayon"))]
1004 fa.into_iter().filter(|a| f(a)).collect()
1005 }
1006
1007 #[document_signature]
1012 #[document_type_parameters(
1014 "The lifetime of the elements.",
1015 "The element type.",
1016 "The monoid type."
1017 )]
1018 #[document_parameters(
1020 "The function mapping each element to a monoid value. Must be `Send + Sync`.",
1021 "The vector to fold."
1022 )]
1023 #[document_returns("The combined monoid value.")]
1025 #[document_examples]
1027 pub fn par_fold_map<'a, A: 'a + Send, M: Monoid + Send + 'a>(
1035 f: impl Fn(A) -> M + Send + Sync + 'a,
1036 fa: Vec<A>,
1037 ) -> M {
1038 #[cfg(feature = "rayon")]
1039 {
1040 use rayon::prelude::*;
1041 fa.into_par_iter().map(f).reduce(M::empty, |acc, m| M::append(acc, m))
1042 }
1043 #[cfg(not(feature = "rayon"))]
1044 fa.into_iter().map(f).fold(M::empty(), |acc, m| M::append(acc, m))
1045 }
1046
1047 #[document_signature]
1052 #[document_type_parameters(
1054 "The lifetime of the elements.",
1055 "The input element type.",
1056 "The output element type."
1057 )]
1058 #[document_parameters(
1060 "The function to apply to each index and element. Must be `Send + Sync`.",
1061 "The vector to map over."
1062 )]
1063 #[document_returns("A new vector containing the mapped elements.")]
1065 #[document_examples]
1067 pub fn par_map_with_index<'a, A: 'a + Send, B: 'a + Send>(
1075 f: impl Fn(usize, A) -> B + Send + Sync + 'a,
1076 fa: Vec<A>,
1077 ) -> Vec<B> {
1078 #[cfg(feature = "rayon")]
1079 {
1080 use rayon::prelude::*;
1081 fa.into_par_iter().enumerate().map(|(i, a)| f(i, a)).collect()
1082 }
1083 #[cfg(not(feature = "rayon"))]
1084 fa.into_iter().enumerate().map(|(i, a)| f(i, a)).collect()
1085 }
1086
1087 #[document_signature]
1092 #[document_type_parameters(
1094 "The lifetime of the elements.",
1095 "The element type.",
1096 "The monoid type."
1097 )]
1098 #[document_parameters(
1100 "The function mapping each index and element to a monoid value. Must be `Send + Sync`.",
1101 "The vector to fold."
1102 )]
1103 #[document_returns("The combined monoid value.")]
1105 #[document_examples]
1107 pub fn par_fold_map_with_index<'a, A: 'a + Send, M: Monoid + Send + 'a>(
1116 f: impl Fn(usize, A) -> M + Send + Sync + 'a,
1117 fa: Vec<A>,
1118 ) -> M {
1119 #[cfg(feature = "rayon")]
1120 {
1121 use rayon::prelude::*;
1122 fa.into_par_iter()
1123 .enumerate()
1124 .map(|(i, a)| f(i, a))
1125 .reduce(M::empty, |acc, m| M::append(acc, m))
1126 }
1127 #[cfg(not(feature = "rayon"))]
1128 fa.into_iter()
1129 .enumerate()
1130 .map(|(i, a)| f(i, a))
1131 .fold(M::empty(), |acc, m| M::append(acc, m))
1132 }
1133
1134 #[document_signature]
1140 #[document_type_parameters(
1142 "The lifetime of the elements.",
1143 "The input element type.",
1144 "The output element type."
1145 )]
1146 #[document_parameters(
1148 "The function to apply to each index and element. Must be `Send + Sync`.",
1149 "The vector to filter and map."
1150 )]
1151 #[document_returns("A new vector containing the `Some` results of applying `f`.")]
1153 #[document_examples]
1155 pub fn par_filter_map_with_index<'a, A: 'a + Send, B: 'a + Send>(
1166 f: impl Fn(usize, A) -> Option<B> + Send + Sync + 'a,
1167 fa: Vec<A>,
1168 ) -> Vec<B> {
1169 #[cfg(feature = "rayon")]
1170 {
1171 use rayon::prelude::*;
1172 fa.into_par_iter().enumerate().filter_map(|(i, a)| f(i, a)).collect()
1173 }
1174 #[cfg(not(feature = "rayon"))]
1175 fa.into_iter().enumerate().filter_map(|(i, a)| f(i, a)).collect()
1176 }
1177
1178 #[document_signature]
1183 #[document_type_parameters("The lifetime of the elements.", "The element type.")]
1185 #[document_parameters(
1187 "The predicate receiving the index and a reference to the element. Must be `Send + Sync`.",
1188 "The vector to filter."
1189 )]
1190 #[document_returns("A new vector containing only the elements satisfying `f`.")]
1192 #[document_examples]
1194 pub fn par_filter_with_index<'a, A: 'a + Send>(
1203 f: impl Fn(usize, &A) -> bool + Send + Sync + 'a,
1204 fa: Vec<A>,
1205 ) -> Vec<A> {
1206 #[cfg(feature = "rayon")]
1207 {
1208 use rayon::prelude::*;
1209 fa.into_par_iter().enumerate().filter(|(i, a)| f(*i, a)).map(|(_, a)| a).collect()
1210 }
1211 #[cfg(not(feature = "rayon"))]
1212 fa.into_iter().enumerate().filter(|(i, a)| f(*i, a)).map(|(_, a)| a).collect()
1213 }
1214 }
1215
1216 impl ParFunctor for VecBrand {
1217 #[document_signature]
1221 #[document_type_parameters(
1223 "The lifetime of the elements.",
1224 "The input element type.",
1225 "The output element type."
1226 )]
1227 #[document_parameters(
1229 "The function to apply to each element. Must be `Send + Sync`.",
1230 "The vector to map over."
1231 )]
1232 #[document_returns("A new vector containing the mapped elements.")]
1234 #[document_examples]
1236 fn par_map<'a, A: 'a + Send, B: 'a + Send>(
1247 f: impl Fn(A) -> B + Send + Sync + 'a,
1248 fa: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
1249 ) -> Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>) {
1250 VecBrand::par_map(f, fa)
1251 }
1252 }
1253
1254 impl ParCompactable for VecBrand {
1255 #[document_signature]
1259 #[document_type_parameters("The lifetime of the elements.", "The element type.")]
1261 #[document_parameters("The vector of options.")]
1263 #[document_returns("A new vector containing the unwrapped `Some` values.")]
1265 #[document_examples]
1267 fn par_compact<'a, A: 'a + Send>(
1278 fa: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<
1279 'a,
1280 Apply!(<OptionBrand as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
1281 >)
1282 ) -> Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>) {
1283 VecBrand::par_compact(fa)
1284 }
1285
1286 #[document_signature]
1290 #[document_type_parameters(
1292 "The lifetime of the elements.",
1293 "The error type.",
1294 "The success type."
1295 )]
1296 #[document_parameters("The vector of results.")]
1298 #[document_returns(
1300 "A pair `(errs, oks)` where `errs` contains the `Err` values and `oks` the `Ok` values."
1301 )]
1302 #[document_examples]
1304 fn par_separate<'a, E: 'a + Send, O: 'a + Send>(
1317 fa: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, Result<O, E>>)
1318 ) -> (
1319 Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, E>),
1320 Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, O>),
1321 ) {
1322 VecBrand::par_separate(fa)
1323 }
1324 }
1325
1326 impl ParFilterable for VecBrand {
1327 #[document_signature]
1332 #[document_type_parameters(
1334 "The lifetime of the elements.",
1335 "The input element type.",
1336 "The output element type."
1337 )]
1338 #[document_parameters(
1340 "The function to apply. Must be `Send + Sync`.",
1341 "The vector to filter and map."
1342 )]
1343 #[document_returns("A new vector containing the `Some` results of applying `f`.")]
1345 #[document_examples]
1347 fn par_filter_map<'a, A: 'a + Send, B: 'a + Send>(
1361 f: impl Fn(A) -> Option<B> + Send + Sync + 'a,
1362 fa: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
1363 ) -> Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>) {
1364 VecBrand::par_filter_map(f, fa)
1365 }
1366
1367 #[document_signature]
1372 #[document_type_parameters("The lifetime of the elements.", "The element type.")]
1374 #[document_parameters("The predicate. Must be `Send + Sync`.", "The vector to filter.")]
1376 #[document_returns("A new vector containing only the elements satisfying `f`.")]
1378 #[document_examples]
1380 fn par_filter<'a, A: 'a + Send>(
1391 f: impl Fn(&A) -> bool + Send + Sync + 'a,
1392 fa: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
1393 ) -> Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>) {
1394 VecBrand::par_filter(f, fa)
1395 }
1396 }
1397
1398 impl ParFoldable for VecBrand {
1399 #[document_signature]
1403 #[document_type_parameters(
1405 "The lifetime of the elements.",
1406 "The element type.",
1407 "The monoid type."
1408 )]
1409 #[document_parameters(
1411 "The function mapping each element to a monoid value. Must be `Send + Sync`.",
1412 "The vector to fold."
1413 )]
1414 #[document_returns("The combined monoid value.")]
1416 #[document_examples]
1418 fn par_fold_map<'a, A: 'a + Send, M: Monoid + Send + 'a>(
1429 f: impl Fn(A) -> M + Send + Sync + 'a,
1430 fa: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
1431 ) -> M {
1432 VecBrand::par_fold_map(f, fa)
1433 }
1434 }
1435
1436 impl ParFunctorWithIndex for VecBrand {
1437 #[document_signature]
1441 #[document_type_parameters(
1443 "The lifetime of the elements.",
1444 "The input element type.",
1445 "The output element type."
1446 )]
1447 #[document_parameters(
1449 "The function to apply to each index and element. Must be `Send + Sync`.",
1450 "The vector to map over."
1451 )]
1452 #[document_returns("A new vector containing the mapped elements.")]
1454 #[document_examples]
1456 fn par_map_with_index<'a, A: 'a + Send, B: 'a + Send>(
1467 f: impl Fn(usize, A) -> B + Send + Sync + 'a,
1468 fa: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
1469 ) -> Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>)
1470 where
1471 usize: Send + Sync + Copy + 'a, {
1472 VecBrand::par_map_with_index(f, fa)
1473 }
1474 }
1475
1476 impl ParFoldableWithIndex for VecBrand {
1477 #[document_signature]
1481 #[document_type_parameters(
1483 "The lifetime of the elements.",
1484 "The element type.",
1485 "The monoid type."
1486 )]
1487 #[document_parameters(
1489 "The function mapping each index and element to a monoid value. Must be `Send + Sync`.",
1490 "The vector to fold."
1491 )]
1492 #[document_returns("The combined monoid value.")]
1494 #[document_examples]
1496 fn par_fold_map_with_index<'a, A: 'a + Send, M: Monoid + Send + 'a>(
1508 f: impl Fn(usize, A) -> M + Send + Sync + 'a,
1509 fa: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
1510 ) -> M
1511 where
1512 usize: Send + Sync + Copy + 'a, {
1513 VecBrand::par_fold_map_with_index(f, fa)
1514 }
1515 }
1516
1517 impl Compactable for VecBrand {
1518 #[document_signature]
1522 #[document_type_parameters("The lifetime of the elements.", "The type of the elements.")]
1524 #[document_parameters("The vector of options.")]
1526 #[document_returns("The flattened vector.")]
1528 #[document_examples]
1530 fn compact<'a, A: 'a>(
1542 fa: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<
1543 'a,
1544 Apply!(<OptionBrand as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
1545 >)
1546 ) -> Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>) {
1547 fa.into_iter().flatten().collect()
1548 }
1549
1550 #[document_signature]
1554 #[document_type_parameters(
1556 "The lifetime of the elements.",
1557 "The type of the error value.",
1558 "The type of the success value."
1559 )]
1560 #[document_parameters("The vector of results.")]
1562 #[document_returns("A pair of vectors.")]
1564 #[document_examples]
1566 fn separate<'a, E: 'a, O: 'a>(
1579 fa: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, Result<O, E>>)
1580 ) -> (
1581 Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, E>),
1582 Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, O>),
1583 ) {
1584 let mut oks = Vec::new();
1585 let mut errs = Vec::new();
1586 for result in fa {
1587 match result {
1588 Ok(o) => oks.push(o),
1589 Err(e) => errs.push(e),
1590 }
1591 }
1592 (errs, oks)
1593 }
1594 }
1595
1596 impl RefCompactable for VecBrand {
1597 #[document_signature]
1602 #[document_type_parameters(
1604 "The lifetime of the elements.",
1605 "The type of the elements in the [`Option`]. Must be [`Clone`] because elements are extracted from a borrowed container."
1606 )]
1607 #[document_parameters("A reference to the vector containing [`Option`] values.")]
1609 #[document_returns(
1611 "A new vector containing only the cloned values from the [`Some`] variants."
1612 )]
1613 #[document_examples]
1615 fn ref_compact<'a, A: 'a + Clone>(
1627 fa: &Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, Option<A>>)
1628 ) -> Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>) {
1629 fa.iter().filter_map(|opt| opt.as_ref().cloned()).collect()
1630 }
1631
1632 #[document_signature]
1637 #[document_type_parameters(
1639 "The lifetime of the elements.",
1640 "The type of the error values. Must be [`Clone`] because elements are extracted from a borrowed container.",
1641 "The type of the success values. Must be [`Clone`] because elements are extracted from a borrowed container."
1642 )]
1643 #[document_parameters("A reference to the vector containing [`Result`] values.")]
1645 #[document_returns(
1647 "A pair of vectors: the first containing the cloned [`Err`] values, and the second containing the cloned [`Ok`] values."
1648 )]
1649 #[document_examples]
1651 fn ref_separate<'a, E: 'a + Clone, O: 'a + Clone>(
1664 fa: &Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, Result<O, E>>)
1665 ) -> (
1666 Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, E>),
1667 Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, O>),
1668 ) {
1669 let mut errs = Vec::new();
1670 let mut oks = Vec::new();
1671 for result in fa.iter() {
1672 match result {
1673 Ok(o) => oks.push(o.clone()),
1674 Err(e) => errs.push(e.clone()),
1675 }
1676 }
1677 (errs, oks)
1678 }
1679 }
1680
1681 impl Filterable for VecBrand {
1682 #[document_signature]
1686 #[document_type_parameters(
1688 "The lifetime of the elements.",
1689 "The type of the input value.",
1690 "The type of the error value.",
1691 "The type of the success value."
1692 )]
1693 #[document_parameters("The function to apply.", "The vector to partition.")]
1695 #[document_returns("A pair of vectors.")]
1697 #[document_examples]
1699 fn partition_map<'a, A: 'a, E: 'a, O: 'a>(
1715 func: impl Fn(A) -> Result<O, E> + 'a,
1716 fa: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
1717 ) -> (
1718 Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, E>),
1719 Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, O>),
1720 ) {
1721 let mut oks = Vec::new();
1722 let mut errs = Vec::new();
1723 for a in fa {
1724 match func(a) {
1725 Ok(o) => oks.push(o),
1726 Err(e) => errs.push(e),
1727 }
1728 }
1729 (errs, oks)
1730 }
1731
1732 #[document_signature]
1736 #[document_type_parameters("The lifetime of the elements.", "The type of the elements.")]
1738 #[document_parameters("The predicate.", "The vector to partition.")]
1740 #[document_returns("A pair of vectors.")]
1742 #[document_examples]
1744 fn partition<'a, A: 'a + Clone>(
1757 func: impl Fn(A) -> bool + 'a,
1758 fa: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
1759 ) -> (
1760 Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
1761 Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
1762 ) {
1763 let (satisfied, not_satisfied): (Vec<A>, Vec<A>) =
1764 fa.into_iter().partition(|a| func(a.clone()));
1765 (not_satisfied, satisfied)
1766 }
1767
1768 #[document_signature]
1772 #[document_type_parameters(
1774 "The lifetime of the elements.",
1775 "The type of the input value.",
1776 "The type of the result of applying the function."
1777 )]
1778 #[document_parameters("The function to apply.", "The vector to filter and map.")]
1780 #[document_returns("The filtered and mapped vector.")]
1782 #[document_examples]
1784 fn filter_map<'a, A: 'a, B: 'a>(
1799 func: impl Fn(A) -> Option<B> + 'a,
1800 fa: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
1801 ) -> Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>) {
1802 fa.into_iter().filter_map(func).collect()
1803 }
1804
1805 #[document_signature]
1809 #[document_type_parameters("The lifetime of the elements.", "The type of the elements.")]
1811 #[document_parameters("The predicate.", "The vector to filter.")]
1813 #[document_returns("The filtered vector.")]
1815 #[document_examples]
1817 fn filter<'a, A: 'a + Clone>(
1829 func: impl Fn(A) -> bool + 'a,
1830 fa: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
1831 ) -> Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>) {
1832 fa.into_iter().filter(|a| func(a.clone())).collect()
1833 }
1834 }
1835
1836 impl FilterableWithIndex for VecBrand {
1837 #[document_signature]
1839 #[document_type_parameters(
1841 "The lifetime of the elements.",
1842 "The type of the input value.",
1843 "The type of the error value.",
1844 "The type of the success value."
1845 )]
1846 #[document_parameters(
1848 "The function to apply to each element and its index.",
1849 "The vector to partition."
1850 )]
1851 #[document_returns("A pair of vectors.")]
1853 #[document_examples]
1855 fn partition_map_with_index<'a, A: 'a, E: 'a, O: 'a>(
1871 func: impl Fn(usize, A) -> Result<O, E> + 'a,
1872 fa: Vec<A>,
1873 ) -> (Vec<E>, Vec<O>) {
1874 let mut oks = Vec::new();
1875 let mut errs = Vec::new();
1876 for (i, a) in fa.into_iter().enumerate() {
1877 match func(i, a) {
1878 Ok(o) => oks.push(o),
1879 Err(e) => errs.push(e),
1880 }
1881 }
1882 (errs, oks)
1883 }
1884
1885 #[document_signature]
1887 #[document_type_parameters("The lifetime of the elements.", "The type of the elements.")]
1889 #[document_parameters(
1891 "The predicate receiving the index and element.",
1892 "The vector to partition."
1893 )]
1894 #[document_returns("A pair of vectors.")]
1896 #[document_examples]
1898 fn partition_with_index<'a, A: 'a + Clone>(
1912 func: impl Fn(usize, A) -> bool + 'a,
1913 fa: Vec<A>,
1914 ) -> (Vec<A>, Vec<A>) {
1915 let mut satisfied = Vec::new();
1916 let mut not_satisfied = Vec::new();
1917 for (i, a) in fa.into_iter().enumerate() {
1918 if func(i, a.clone()) {
1919 satisfied.push(a);
1920 } else {
1921 not_satisfied.push(a);
1922 }
1923 }
1924 (not_satisfied, satisfied)
1925 }
1926
1927 #[document_signature]
1929 #[document_type_parameters(
1931 "The lifetime of the elements.",
1932 "The type of the input value.",
1933 "The type of the result of applying the function."
1934 )]
1935 #[document_parameters(
1937 "The function to apply to each element and its index.",
1938 "The vector to filter and map."
1939 )]
1940 #[document_returns("The filtered and mapped vector.")]
1942 #[document_examples]
1944 fn filter_map_with_index<'a, A: 'a, B: 'a>(
1959 func: impl Fn(usize, A) -> Option<B> + 'a,
1960 fa: Vec<A>,
1961 ) -> Vec<B> {
1962 fa.into_iter().enumerate().filter_map(|(i, a)| func(i, a)).collect()
1963 }
1964
1965 #[document_signature]
1967 #[document_type_parameters("The lifetime of the elements.", "The type of the elements.")]
1969 #[document_parameters(
1971 "The predicate receiving the index and element.",
1972 "The vector to filter."
1973 )]
1974 #[document_returns("The filtered vector.")]
1976 #[document_examples]
1978 fn filter_with_index<'a, A: 'a + Clone>(
1990 func: impl Fn(usize, A) -> bool + 'a,
1991 fa: Vec<A>,
1992 ) -> Vec<A> {
1993 fa.into_iter()
1994 .enumerate()
1995 .filter(|(i, a)| func(*i, a.clone()))
1996 .map(|(_, a)| a)
1997 .collect()
1998 }
1999 }
2000
2001 impl ParFilterableWithIndex for VecBrand {
2002 #[document_signature]
2008 #[document_type_parameters(
2010 "The lifetime of the elements.",
2011 "The input element type.",
2012 "The output element type."
2013 )]
2014 #[document_parameters(
2016 "The function to apply to each index and element. Must be `Send + Sync`.",
2017 "The vector to filter and map."
2018 )]
2019 #[document_returns("A new vector containing the `Some` results of applying `f`.")]
2021 #[document_examples]
2023 fn par_filter_map_with_index<'a, A: 'a + Send, B: 'a + Send>(
2037 f: impl Fn(usize, A) -> Option<B> + Send + Sync + 'a,
2038 fa: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
2039 ) -> Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>)
2040 where
2041 usize: Send + Sync + Copy + 'a, {
2042 VecBrand::par_filter_map_with_index(f, fa)
2043 }
2044
2045 #[document_signature]
2050 #[document_type_parameters("The lifetime of the elements.", "The element type.")]
2052 #[document_parameters(
2054 "The predicate receiving the index and a reference to the element. Must be `Send + Sync`.",
2055 "The vector to filter."
2056 )]
2057 #[document_returns("A new vector containing only the elements satisfying `f`.")]
2059 #[document_examples]
2061 fn par_filter_with_index<'a, A: 'a + Send>(
2073 f: impl Fn(usize, &A) -> bool + Send + Sync + 'a,
2074 fa: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
2075 ) -> Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>)
2076 where
2077 usize: Send + Sync + Copy + 'a, {
2078 VecBrand::par_filter_with_index(f, fa)
2079 }
2080 }
2081
2082 impl Witherable for VecBrand {
2083 #[document_signature]
2087 #[document_type_parameters(
2089 "The lifetime of the elements.",
2090 "The applicative context.",
2091 "The type of the input value.",
2092 "The type of the error value.",
2093 "The type of the success value."
2094 )]
2095 #[document_parameters("The function to apply.", "The vector to partition.")]
2097 #[document_returns("The partitioned vector wrapped in the applicative context.")]
2099 #[document_examples]
2101 fn wilt<'a, M: Applicative, A: 'a + Clone, E: 'a + Clone, O: 'a + Clone>(
2116 func: impl Fn(A) -> Apply!(<M as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, Result<O, E>>)
2117 + 'a,
2118 ta: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
2119 ) -> Apply!(<M as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<
2120 'a,
2121 (
2122 Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, E>),
2123 Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, O>),
2124 ),
2125 >)
2126 where
2127 Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, Result<O, E>>): Clone,
2128 Apply!(<M as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, Result<O, E>>): Clone, {
2129 ta.into_iter().fold(M::pure((Vec::new(), Vec::new())), |acc, x| {
2130 M::lift2(
2131 |mut pair, res| {
2132 match res {
2133 Ok(o) => pair.1.push(o),
2134 Err(e) => pair.0.push(e),
2135 }
2136 pair
2137 },
2138 acc,
2139 func(x),
2140 )
2141 })
2142 }
2143
2144 #[document_signature]
2148 #[document_type_parameters(
2150 "The lifetime of the values.",
2151 "The applicative context.",
2152 "The type of the elements in the input structure.",
2153 "The type of the result of applying the function."
2154 )]
2155 #[document_parameters(
2157 "The function to apply to each element, returning an `Option` in an applicative context.",
2158 "The vector to filter and map."
2159 )]
2160 #[document_returns("The filtered and mapped vector wrapped in the applicative context.")]
2162 #[document_examples]
2163 fn wither<'a, M: Applicative, A: 'a + Clone, B: 'a + Clone>(
2178 func: impl Fn(A) -> Apply!(<M as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, Option<B>>) + 'a,
2179 ta: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
2180 ) -> Apply!(<M as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<
2181 'a,
2182 Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>),
2183 >)
2184 where
2185 Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, Option<B>>): Clone,
2186 Apply!(<M as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, Option<B>>): Clone, {
2187 ta.into_iter().fold(M::pure(Vec::new()), |acc, x| {
2188 M::lift2(
2189 |mut v, opt_b| {
2190 if let Some(b) = opt_b {
2191 v.push(b);
2192 }
2193 v
2194 },
2195 acc,
2196 func(x),
2197 )
2198 })
2199 }
2200 }
2201
2202 impl Extend for VecBrand {
2211 #[document_signature]
2217 #[document_type_parameters(
2219 "The lifetime of the values.",
2220 "The type of the elements in the vector.",
2221 "The result type of the extension function."
2222 )]
2223 #[document_parameters(
2225 "The function that consumes a suffix vector and produces a value.",
2226 "The vector to extend over."
2227 )]
2228 #[document_returns(
2230 "A new vector containing the results of applying the function to each suffix."
2231 )]
2232 #[document_examples]
2234 fn extend<'a, A: 'a + Clone, B: 'a>(
2245 f: impl Fn(Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>)) -> B + 'a,
2246 wa: Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
2247 ) -> Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>) {
2248 (0 .. wa.len()).map(|i| f(wa.get(i ..).unwrap_or_default().to_vec())).collect()
2249 }
2250 }
2251
2252 impl MonadRec for VecBrand {
2253 #[document_signature]
2260 #[document_type_parameters(
2262 "The lifetime of the computation.",
2263 "The type of the initial value and loop state.",
2264 "The type of the result."
2265 )]
2266 #[document_parameters("The step function.", "The initial value.")]
2268 #[document_returns("A vector of all completed results.")]
2270 #[document_examples]
2272 fn tail_rec_m<'a, A: 'a, B: 'a>(
2298 func: impl Fn(
2299 A,
2300 )
2301 -> Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, ControlFlow<B, A>>)
2302 + 'a,
2303 initial: A,
2304 ) -> Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>) {
2305 let mut done: Vec<B> = Vec::new();
2306 let mut pending: Vec<A> = vec![initial];
2307 while !pending.is_empty() {
2308 let mut next_pending: Vec<A> = Vec::new();
2309 for a in pending {
2310 for step in func(a) {
2311 match step {
2312 ControlFlow::Continue(next) => next_pending.push(next),
2313 ControlFlow::Break(b) => done.push(b),
2314 }
2315 }
2316 }
2317 pending = next_pending;
2318 }
2319 done
2320 }
2321 }
2322
2323 impl RefFunctor for VecBrand {
2326 #[document_signature]
2328 #[document_type_parameters(
2330 "The lifetime of the elements.",
2331 "The type of the elements in the vector.",
2332 "The type of the elements in the resulting vector."
2333 )]
2334 #[document_parameters(
2336 "The function to apply to each element reference.",
2337 "The vector to map over."
2338 )]
2339 #[document_returns("A new vector containing the results.")]
2341 #[document_examples]
2343 fn ref_map<'a, A: 'a, B: 'a>(
2356 func: impl Fn(&A) -> B + 'a,
2357 fa: &Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
2358 ) -> Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>) {
2359 fa.iter().map(func).collect()
2360 }
2361 }
2362
2363 impl RefFoldable for VecBrand {
2364 #[document_signature]
2366 #[document_type_parameters(
2368 "The lifetime of the elements.",
2369 "The brand of the cloneable function wrapper.",
2370 "The type of the elements.",
2371 "The monoid type."
2372 )]
2373 #[document_parameters(
2375 "The function to map each element reference to a monoid.",
2376 "The vector to fold."
2377 )]
2378 #[document_returns("The combined monoid value.")]
2380 #[document_examples]
2382 fn ref_fold_map<'a, FnBrand, A: 'a + Clone, M>(
2394 func: impl Fn(&A) -> M + 'a,
2395 fa: &Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
2396 ) -> M
2397 where
2398 FnBrand: LiftFn + 'a,
2399 M: Monoid + 'a, {
2400 fa.iter().fold(Monoid::empty(), |acc, a| Semigroup::append(acc, func(a)))
2401 }
2402 }
2403
2404 impl RefFilterable for VecBrand {
2405 #[document_signature]
2407 #[document_type_parameters(
2409 "The lifetime of the elements.",
2410 "The type of the input elements.",
2411 "The type of the output elements."
2412 )]
2413 #[document_parameters("The filter-map function.", "The vector to filter.")]
2415 #[document_returns("The filtered vector.")]
2417 #[document_examples]
2419 fn ref_filter_map<'a, A: 'a, B: 'a>(
2434 func: impl Fn(&A) -> Option<B> + 'a,
2435 fa: &Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
2436 ) -> Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>) {
2437 fa.iter().filter_map(func).collect()
2438 }
2439 }
2440
2441 impl RefTraversable for VecBrand {
2442 #[document_signature]
2444 #[document_type_parameters(
2446 "The lifetime of the elements.",
2447 "The brand of the cloneable function wrapper.",
2448 "The type of the input elements.",
2449 "The type of the output elements.",
2450 "The applicative functor brand."
2451 )]
2452 #[document_parameters(
2454 "The function to apply to each element reference.",
2455 "The vector to traverse."
2456 )]
2457 #[document_returns("The combined result in the applicative context.")]
2459 #[document_examples]
2461 fn ref_traverse<'a, FnBrand, A: 'a + Clone, B: 'a + Clone, F: Applicative>(
2474 func: impl Fn(&A) -> Apply!(<F as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>) + 'a,
2475 ta: &Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
2476 ) -> 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>)>)
2477 where
2478 FnBrand: LiftFn + 'a,
2479 Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>): Clone,
2480 Apply!(<F as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>): Clone, {
2481 let len = ta.len();
2482 ta.iter().fold(
2483 F::pure::<Vec<B>>(Vec::with_capacity(len)),
2484 |acc: Apply!(<F as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, Vec<B>>), a| {
2485 F::lift2(
2486 |mut v: Vec<B>, b: B| {
2487 v.push(b);
2488 v
2489 },
2490 acc,
2491 func(a),
2492 )
2493 },
2494 )
2495 }
2496 }
2497
2498 impl RefWitherable for VecBrand {}
2499
2500 impl RefFunctorWithIndex for VecBrand {
2501 #[document_signature]
2503 #[document_type_parameters(
2505 "The lifetime of the elements.",
2506 "The type of the input elements.",
2507 "The type of the output elements."
2508 )]
2509 #[document_parameters("The function to apply.", "The vector to map over.")]
2511 #[document_returns("The mapped vector.")]
2513 #[document_examples]
2515 fn ref_map_with_index<'a, A: 'a, B: 'a>(
2528 func: impl Fn(usize, &A) -> B + 'a,
2529 fa: &Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
2530 ) -> Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>) {
2531 fa.iter().enumerate().map(|(i, a)| func(i, a)).collect()
2532 }
2533 }
2534
2535 impl RefFoldableWithIndex for VecBrand {
2536 #[document_signature]
2538 #[document_type_parameters(
2540 "The lifetime of the elements.",
2541 "The brand of the cloneable function to use.",
2542 "The type of the elements.",
2543 "The monoid type."
2544 )]
2545 #[document_parameters(
2547 "The function to map each (index, element reference) pair.",
2548 "The vector to fold."
2549 )]
2550 #[document_returns("The combined monoid value.")]
2552 #[document_examples]
2554 fn ref_fold_map_with_index<'a, FnBrand, A: 'a + Clone, R: Monoid + 'a>(
2569 func: impl Fn(usize, &A) -> R + 'a,
2570 fa: &Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
2571 ) -> R
2572 where
2573 FnBrand: LiftFn + 'a, {
2574 fa.iter()
2575 .enumerate()
2576 .fold(Monoid::empty(), |acc, (i, a)| Semigroup::append(acc, func(i, a)))
2577 }
2578 }
2579
2580 impl RefFilterableWithIndex for VecBrand {
2581 #[document_signature]
2583 #[document_type_parameters(
2585 "The lifetime of the elements.",
2586 "The type of the input elements.",
2587 "The type of the output elements."
2588 )]
2589 #[document_parameters("The filter-map function.", "The vector to filter.")]
2591 #[document_returns("The filtered vector.")]
2593 #[document_examples]
2595 fn ref_filter_map_with_index<'a, A: 'a, B: 'a>(
2610 func: impl Fn(usize, &A) -> Option<B> + 'a,
2611 fa: &Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
2612 ) -> Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>) {
2613 fa.iter().enumerate().filter_map(|(i, a)| func(i, a)).collect()
2614 }
2615 }
2616
2617 impl RefTraversableWithIndex for VecBrand {
2618 #[document_signature]
2620 #[document_type_parameters(
2622 "The lifetime of the elements.",
2623 "The type of the input elements.",
2624 "The type of the output elements.",
2625 "The applicative functor brand."
2626 )]
2627 #[document_parameters("The function to apply.", "The vector to traverse.")]
2629 #[document_returns("The combined result in the applicative context.")]
2631 #[document_examples]
2633 fn ref_traverse_with_index<'a, A: 'a + Clone, B: 'a + Clone, M: Applicative>(
2649 f: impl Fn(usize, &A) -> Apply!(<M as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>) + 'a,
2650 ta: &Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
2651 ) -> Apply!(<M as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>)>)
2652 where
2653 Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>): Clone,
2654 Apply!(<M as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>): Clone, {
2655 let len = ta.len();
2656 ta.iter().enumerate().fold(
2657 M::pure::<Vec<B>>(Vec::with_capacity(len)),
2658 |acc: Apply!(<M as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, Vec<B>>), (i, a)| {
2659 M::lift2(
2660 |mut v: Vec<B>, b: B| {
2661 v.push(b);
2662 v
2663 },
2664 acc,
2665 f(i, a),
2666 )
2667 },
2668 )
2669 }
2670 }
2671
2672 impl RefPointed for VecBrand {
2675 #[document_signature]
2677 #[document_type_parameters("The lifetime of the value.", "The type of the value.")]
2679 #[document_parameters("The reference to the value to wrap.")]
2681 #[document_returns("A singleton vector containing a clone of the value.")]
2683 #[document_examples]
2685 fn ref_pure<'a, A: Clone + 'a>(
2697 a: &A
2698 ) -> Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>) {
2699 vec![a.clone()]
2700 }
2701 }
2702
2703 impl RefLift for VecBrand {
2704 #[document_signature]
2706 #[document_type_parameters(
2708 "The lifetime of the values.",
2709 "The type of the first input.",
2710 "The type of the second input.",
2711 "The type of the output."
2712 )]
2713 #[document_parameters(
2715 "The binary function receiving references.",
2716 "The first vector.",
2717 "The second vector."
2718 )]
2719 #[document_returns("A new vector with the combined results.")]
2721 #[document_examples]
2723 fn ref_lift2<'a, A: 'a, B: 'a, C: 'a>(
2738 func: impl Fn(&A, &B) -> C + 'a,
2739 fa: &Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
2740 fb: &Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>),
2741 ) -> Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, C>) {
2742 let func = &func;
2743 fa.iter().flat_map(|a| fb.iter().map(move |b| func(a, b))).collect()
2744 }
2745 }
2746
2747 impl RefSemiapplicative for VecBrand {
2748 #[document_signature]
2750 #[document_type_parameters(
2752 "The lifetime of the values.",
2753 "The brand of the cloneable function wrapper.",
2754 "The type of the input values.",
2755 "The type of the output values."
2756 )]
2757 #[document_parameters(
2759 "The vector containing the by-ref functions.",
2760 "The vector containing the values."
2761 )]
2762 #[document_returns("A new vector with each function applied to each value by reference.")]
2764 #[document_examples]
2766 fn ref_apply<'a, FnBrand: 'a + CloneFn<Ref>, A: 'a, B: 'a>(
2780 ff: &Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, <FnBrand as CloneFn<Ref>>::Of<'a, A, B>>),
2781 fa: &Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
2782 ) -> Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>) {
2783 ff.iter().flat_map(|f| fa.iter().map(move |a| (**f)(a))).collect()
2784 }
2785 }
2786
2787 impl RefSemimonad for VecBrand {
2788 #[document_signature]
2790 #[document_type_parameters(
2792 "The lifetime of the values.",
2793 "The type of the input values.",
2794 "The type of the output values."
2795 )]
2796 #[document_parameters(
2798 "The input vector.",
2799 "The function to apply to each element by reference."
2800 )]
2801 #[document_returns("A new vector with the results flattened.")]
2803 #[document_examples]
2805 fn ref_bind<'a, A: 'a, B: 'a>(
2817 fa: &Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
2818 f: impl Fn(&A) -> Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>) + 'a,
2819 ) -> Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>) {
2820 fa.iter().flat_map(f).collect()
2821 }
2822 }
2823
2824 impl ParRefFunctor for VecBrand {
2827 #[document_signature]
2828 #[document_type_parameters(
2829 "The lifetime.",
2830 "The input element type.",
2831 "The output element type."
2832 )]
2833 #[document_parameters("The function. Must be `Send + Sync`.", "The vector.")]
2834 #[document_returns("A new vector with mapped elements.")]
2835 #[document_examples]
2836 fn par_ref_map<'a, A: Send + Sync + 'a, B: Send + 'a>(
2846 f: impl Fn(&A) -> B + Send + Sync + 'a,
2847 fa: &Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
2848 ) -> Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>) {
2849 #[cfg(feature = "rayon")]
2850 {
2851 use rayon::prelude::*;
2852 fa.par_iter().map(f).collect()
2853 }
2854 #[cfg(not(feature = "rayon"))]
2855 fa.iter().map(f).collect()
2856 }
2857 }
2858
2859 impl ParRefFoldable for VecBrand {
2860 #[document_signature]
2861 #[document_type_parameters("The lifetime.", "The element type.", "The monoid type.")]
2862 #[document_parameters("The function. Must be `Send + Sync`.", "The vector.")]
2863 #[document_returns("The combined monoid value.")]
2864 #[document_examples]
2865 fn par_ref_fold_map<'a, A: Send + Sync + 'a, M: Monoid + Send + 'a>(
2875 f: impl Fn(&A) -> M + Send + Sync + 'a,
2876 fa: &Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
2877 ) -> M {
2878 #[cfg(feature = "rayon")]
2879 {
2880 use rayon::prelude::*;
2881 fa.par_iter().map(f).reduce(Monoid::empty, Semigroup::append)
2882 }
2883 #[cfg(not(feature = "rayon"))]
2884 fa.iter().map(f).fold(Monoid::empty(), |acc, m| Semigroup::append(acc, m))
2885 }
2886 }
2887
2888 impl ParRefFilterable for VecBrand {
2889 #[document_signature]
2890 #[document_type_parameters("The lifetime.", "The input type.", "The output type.")]
2891 #[document_parameters("The function. Must be `Send + Sync`.", "The vector.")]
2892 #[document_returns("A new vector with filtered and mapped elements.")]
2893 #[document_examples]
2894 fn par_ref_filter_map<'a, A: Send + Sync + 'a, B: Send + 'a>(
2907 f: impl Fn(&A) -> Option<B> + Send + Sync + 'a,
2908 fa: &Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
2909 ) -> Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>) {
2910 #[cfg(feature = "rayon")]
2911 {
2912 use rayon::prelude::*;
2913 fa.par_iter().filter_map(f).collect()
2914 }
2915 #[cfg(not(feature = "rayon"))]
2916 fa.iter().filter_map(f).collect()
2917 }
2918 }
2919
2920 impl ParRefFunctorWithIndex for VecBrand {
2921 #[document_signature]
2922 #[document_type_parameters("The lifetime.", "The input type.", "The output type.")]
2923 #[document_parameters("The function with index. Must be `Send + Sync`.", "The vector.")]
2924 #[document_returns("A new vector with mapped elements.")]
2925 #[document_examples]
2926 fn par_ref_map_with_index<'a, A: Send + Sync + 'a, B: Send + 'a>(
2937 f: impl Fn(usize, &A) -> B + Send + Sync + 'a,
2938 fa: &Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
2939 ) -> Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>) {
2940 #[cfg(feature = "rayon")]
2941 {
2942 use rayon::prelude::*;
2943 fa.par_iter().enumerate().map(|(i, a)| f(i, a)).collect()
2944 }
2945 #[cfg(not(feature = "rayon"))]
2946 fa.iter().enumerate().map(|(i, a)| f(i, a)).collect()
2947 }
2948 }
2949
2950 impl ParRefFoldableWithIndex for VecBrand {
2951 #[document_signature]
2952 #[document_type_parameters("The lifetime.", "The element type.", "The monoid type.")]
2953 #[document_parameters("The function with index. Must be `Send + Sync`.", "The vector.")]
2954 #[document_returns("The combined monoid value.")]
2955 #[document_examples]
2956 fn par_ref_fold_map_with_index<'a, A: Send + Sync + 'a, M: Monoid + Send + 'a>(
2967 f: impl Fn(usize, &A) -> M + Send + Sync + 'a,
2968 fa: &Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
2969 ) -> M {
2970 #[cfg(feature = "rayon")]
2971 {
2972 use rayon::prelude::*;
2973 fa.par_iter()
2974 .enumerate()
2975 .map(|(i, a)| f(i, a))
2976 .reduce(Monoid::empty, Semigroup::append)
2977 }
2978 #[cfg(not(feature = "rayon"))]
2979 fa.iter()
2980 .enumerate()
2981 .map(|(i, a)| f(i, a))
2982 .fold(Monoid::empty(), |acc, m| Semigroup::append(acc, m))
2983 }
2984 }
2985
2986 impl ParRefFilterableWithIndex for VecBrand {
2987 #[document_signature]
2988 #[document_type_parameters("The lifetime.", "The input type.", "The output type.")]
2989 #[document_parameters("The function with index. Must be `Send + Sync`.", "The vector.")]
2990 #[document_returns("A new vector with filtered and mapped elements.")]
2991 #[document_examples]
2992 fn par_ref_filter_map_with_index<'a, A: Send + Sync + 'a, B: Send + 'a>(
3006 f: impl Fn(usize, &A) -> Option<B> + Send + Sync + 'a,
3007 fa: &Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
3008 ) -> Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>) {
3009 #[cfg(feature = "rayon")]
3010 {
3011 use rayon::prelude::*;
3012 fa.par_iter().enumerate().filter_map(|(i, a)| f(i, a)).collect()
3013 }
3014 #[cfg(not(feature = "rayon"))]
3015 fa.iter().enumerate().filter_map(|(i, a)| f(i, a)).collect()
3016 }
3017 }
3018}
3019
3020#[cfg(test)]
3021mod tests {
3022
3023 use {
3024 crate::{
3025 brands::*,
3026 classes::*,
3027 functions::*,
3028 },
3029 quickcheck_macros::quickcheck,
3030 };
3031
3032 #[quickcheck]
3036 fn functor_identity(x: Vec<i32>) -> bool {
3037 explicit::map::<VecBrand, _, _, _, _>(identity, x.clone()) == x
3038 }
3039
3040 #[quickcheck]
3042 fn functor_composition(x: Vec<i32>) -> bool {
3043 let f = |x: i32| x.wrapping_add(1);
3044 let g = |x: i32| x.wrapping_mul(2);
3045 explicit::map::<VecBrand, _, _, _, _>(compose(f, g), x.clone())
3046 == explicit::map::<VecBrand, _, _, _, _>(f, explicit::map::<VecBrand, _, _, _, _>(g, x))
3047 }
3048
3049 #[quickcheck]
3053 fn applicative_identity(v: Vec<i32>) -> bool {
3054 apply(pure::<VecBrand, _>(<RcFnBrand as LiftFn>::new(identity)), v.clone()) == v
3055 }
3056
3057 #[quickcheck]
3059 fn applicative_homomorphism(x: i32) -> bool {
3060 let f = |x: i32| x.wrapping_mul(2);
3061 apply(pure::<VecBrand, _>(<RcFnBrand as LiftFn>::new(f)), pure::<VecBrand, _>(x))
3062 == pure::<VecBrand, _>(f(x))
3063 }
3064
3065 #[quickcheck]
3067 fn applicative_composition(
3068 w: Vec<i32>,
3069 u_seeds: Vec<i32>,
3070 v_seeds: Vec<i32>,
3071 ) -> bool {
3072 let u_fns: Vec<_> = u_seeds
3073 .iter()
3074 .map(|&i| <RcFnBrand as LiftFn>::new(move |x: i32| x.wrapping_add(i)))
3075 .collect();
3076 let v_fns: Vec<_> = v_seeds
3077 .iter()
3078 .map(|&i| <RcFnBrand as LiftFn>::new(move |x: i32| x.wrapping_mul(i)))
3079 .collect();
3080
3081 let vw = apply(v_fns.clone(), w.clone());
3083 let rhs = apply(u_fns.clone(), vw);
3084
3085 let uv_fns: Vec<_> = u_fns
3089 .iter()
3090 .flat_map(|uf| {
3091 v_fns.iter().map(move |vf| {
3092 let uf = uf.clone();
3093 let vf = vf.clone();
3094 <RcFnBrand as LiftFn>::new(move |x| uf(vf(x)))
3095 })
3096 })
3097 .collect();
3098
3099 let lhs = apply(uv_fns, w);
3100
3101 lhs == rhs
3102 }
3103
3104 #[quickcheck]
3106 fn applicative_interchange(y: i32) -> bool {
3107 let f = |x: i32| x.wrapping_mul(2);
3109 let u = vec![<RcFnBrand as LiftFn>::new(f)];
3110
3111 let lhs = apply(u.clone(), pure::<VecBrand, _>(y));
3112
3113 let rhs_fn = <RcFnBrand as LiftFn>::new(move |f: std::rc::Rc<dyn Fn(i32) -> i32>| f(y));
3114 let rhs = apply(pure::<VecBrand, _>(rhs_fn), u);
3115
3116 lhs == rhs
3117 }
3118
3119 #[quickcheck]
3123 fn semigroup_associativity(
3124 a: Vec<i32>,
3125 b: Vec<i32>,
3126 c: Vec<i32>,
3127 ) -> bool {
3128 append(a.clone(), append(b.clone(), c.clone())) == append(append(a, b), c)
3129 }
3130
3131 #[quickcheck]
3135 fn monoid_left_identity(a: Vec<i32>) -> bool {
3136 append(empty::<Vec<i32>>(), a.clone()) == a
3137 }
3138
3139 #[quickcheck]
3141 fn monoid_right_identity(a: Vec<i32>) -> bool {
3142 append(a.clone(), empty::<Vec<i32>>()) == a
3143 }
3144
3145 #[quickcheck]
3149 fn monad_left_identity(a: i32) -> bool {
3150 let f = |x: i32| vec![x.wrapping_mul(2)];
3151 explicit::bind::<VecBrand, _, _, _, _>(pure::<VecBrand, _>(a), f) == f(a)
3152 }
3153
3154 #[quickcheck]
3156 fn monad_right_identity(m: Vec<i32>) -> bool {
3157 explicit::bind::<VecBrand, _, _, _, _>(m.clone(), pure::<VecBrand, _>) == m
3158 }
3159
3160 #[quickcheck]
3162 fn monad_associativity(m: Vec<i32>) -> bool {
3163 let f = |x: i32| vec![x.wrapping_mul(2)];
3164 let g = |x: i32| vec![x.wrapping_add(1)];
3165 explicit::bind::<VecBrand, _, _, _, _>(
3166 explicit::bind::<VecBrand, _, _, _, _>(m.clone(), f),
3167 g,
3168 ) == explicit::bind::<VecBrand, _, _, _, _>(m, |x| {
3169 explicit::bind::<VecBrand, _, _, _, _>(f(x), g)
3170 })
3171 }
3172
3173 #[test]
3177 fn map_empty() {
3178 assert_eq!(
3179 explicit::map::<VecBrand, _, _, _, _>(|x: i32| x + 1, vec![] as Vec<i32>),
3180 vec![] as Vec<i32>
3181 );
3182 }
3183
3184 #[test]
3186 fn bind_empty() {
3187 assert_eq!(
3188 explicit::bind::<VecBrand, _, _, _, _>(vec![] as Vec<i32>, |x: i32| vec![x + 1]),
3189 vec![] as Vec<i32>
3190 );
3191 }
3192
3193 #[test]
3195 fn bind_returning_empty() {
3196 assert_eq!(
3197 explicit::bind::<VecBrand, _, _, _, _>(vec![1, 2, 3], |_| vec![] as Vec<i32>),
3198 vec![] as Vec<i32>
3199 );
3200 }
3201
3202 #[test]
3204 fn fold_right_empty() {
3205 assert_eq!(
3206 crate::functions::explicit::fold_right::<RcFnBrand, VecBrand, _, _, _, _>(
3207 |x: i32, acc| x + acc,
3208 0,
3209 vec![]
3210 ),
3211 0
3212 );
3213 }
3214
3215 #[test]
3217 fn fold_left_empty() {
3218 assert_eq!(
3219 crate::functions::explicit::fold_left::<RcFnBrand, VecBrand, _, _, _, _>(
3220 |acc, x: i32| acc + x,
3221 0,
3222 vec![]
3223 ),
3224 0
3225 );
3226 }
3227
3228 #[test]
3230 fn traverse_empty() {
3231 use crate::brands::OptionBrand;
3232 assert_eq!(
3233 crate::classes::traversable::traverse::<VecBrand, _, _, OptionBrand>(
3234 |x: i32| Some(x + 1),
3235 vec![]
3236 ),
3237 Some(vec![])
3238 );
3239 }
3240
3241 #[test]
3243 fn traverse_returning_empty() {
3244 use crate::brands::OptionBrand;
3245 assert_eq!(
3246 crate::classes::traversable::traverse::<VecBrand, _, _, OptionBrand>(
3247 |_: i32| None::<i32>,
3248 vec![1, 2, 3]
3249 ),
3250 None
3251 );
3252 }
3253
3254 #[test]
3256 fn construct_empty_tail() {
3257 assert_eq!(VecBrand::construct(1, vec![]), vec![1]);
3258 }
3259
3260 #[test]
3262 fn deconstruct_empty() {
3263 assert_eq!(VecBrand::deconstruct::<i32>(&[]), None);
3264 }
3265
3266 #[test]
3270 fn par_map_basic() {
3271 let v = vec![1, 2, 3];
3272 let result: Vec<i32> = par_map::<VecBrand, _, _>(|x: i32| x * 2, v);
3273 assert_eq!(result, vec![2, 4, 6]);
3274 }
3275
3276 #[test]
3278 fn par_filter_basic() {
3279 let v = vec![1, 2, 3, 4, 5];
3280 let result: Vec<i32> = par_filter::<VecBrand, _>(|x: &i32| x % 2 == 0, v);
3281 assert_eq!(result, vec![2, 4]);
3282 }
3283
3284 #[test]
3286 fn par_filter_map_basic() {
3287 let v = vec![1, 2, 3, 4, 5];
3288 let result: Vec<i32> = par_filter_map::<VecBrand, _, _>(
3289 |x: i32| if x % 2 == 0 { Some(x * 10) } else { None },
3290 v,
3291 );
3292 assert_eq!(result, vec![20, 40]);
3293 }
3294
3295 #[test]
3297 fn par_compact_basic() {
3298 let v = vec![Some(1), None, Some(3), None, Some(5)];
3299 let result: Vec<i32> = par_compact::<VecBrand, _>(v);
3300 assert_eq!(result, vec![1, 3, 5]);
3301 }
3302
3303 #[test]
3305 fn par_separate_basic() {
3306 let v: Vec<Result<i32, &str>> = vec![Ok(1), Err("a"), Ok(3), Err("b")];
3307 let (errs, oks): (Vec<&str>, Vec<i32>) = par_separate::<VecBrand, _, _>(v);
3308 assert_eq!(errs, vec!["a", "b"]);
3309 assert_eq!(oks, vec![1, 3]);
3310 }
3311
3312 #[test]
3314 fn par_map_with_index_basic() {
3315 let v = vec![10, 20, 30];
3316 let result: Vec<i32> = par_map_with_index::<VecBrand, _, _>(|i, x: i32| x + i as i32, v);
3317 assert_eq!(result, vec![10, 21, 32]);
3318 }
3319
3320 #[test]
3322 fn par_fold_map_empty() {
3323 let v: Vec<i32> = vec![];
3324 assert_eq!(par_fold_map::<VecBrand, _, _>(|x: i32| x.to_string(), v), "".to_string());
3325 }
3326
3327 #[test]
3329 fn par_fold_map_multiple() {
3330 let v = vec![1, 2, 3];
3331 assert_eq!(par_fold_map::<VecBrand, _, _>(|x: i32| x.to_string(), v), "123".to_string());
3332 }
3333
3334 #[test]
3336 fn par_fold_map_with_index_basic() {
3337 let v = vec![10, 20, 30];
3338 let result: String =
3339 par_fold_map_with_index::<VecBrand, _, _>(|i, x: i32| format!("{i}:{x}"), v);
3340 assert_eq!(result, "0:101:202:30");
3341 }
3342
3343 #[quickcheck]
3347 fn filterable_filter_map_identity(x: Vec<Option<i32>>) -> bool {
3348 explicit::filter_map::<VecBrand, _, _, _, _>(identity, x.clone())
3349 == explicit::compact::<VecBrand, _, _, _>(x)
3350 }
3351
3352 #[quickcheck]
3354 fn filterable_filter_map_just(x: Vec<i32>) -> bool {
3355 explicit::filter_map::<VecBrand, _, _, _, _>(Some, x.clone()) == x
3356 }
3357
3358 #[quickcheck]
3360 fn filterable_filter_map_composition(x: Vec<i32>) -> bool {
3361 let r = |i: i32| if i % 2 == 0 { Some(i) } else { None };
3362 let l = |i: i32| if i > 5 { Some(i) } else { None };
3363 let composed = |i| explicit::bind::<OptionBrand, _, _, _, _>(r(i), l);
3364
3365 explicit::filter_map::<VecBrand, _, _, _, _>(composed, x.clone())
3366 == explicit::filter_map::<VecBrand, _, _, _, _>(
3367 l,
3368 explicit::filter_map::<VecBrand, _, _, _, _>(r, x),
3369 )
3370 }
3371
3372 #[quickcheck]
3374 fn filterable_filter_consistency(x: Vec<i32>) -> bool {
3375 let p = |i: i32| i % 2 == 0;
3376 let maybe_bool = |i| if p(i) { Some(i) } else { None };
3377
3378 explicit::filter::<VecBrand, _, _, _>(p, x.clone())
3379 == explicit::filter_map::<VecBrand, _, _, _, _>(maybe_bool, x)
3380 }
3381
3382 #[quickcheck]
3384 fn filterable_partition_map_identity(x: Vec<Result<i32, i32>>) -> bool {
3385 explicit::partition_map::<VecBrand, _, _, _, _, _>(identity, x.clone())
3386 == explicit::separate::<VecBrand, _, _, _, _>(x)
3387 }
3388
3389 #[quickcheck]
3391 fn filterable_partition_map_right_identity(x: Vec<i32>) -> bool {
3392 let (_, oks) = explicit::partition_map::<VecBrand, _, _, _, _, _>(Ok::<_, i32>, x.clone());
3393 oks == x
3394 }
3395
3396 #[quickcheck]
3398 fn filterable_partition_map_left_identity(x: Vec<i32>) -> bool {
3399 let (errs, _) =
3400 explicit::partition_map::<VecBrand, _, _, _, _, _>(Err::<i32, _>, x.clone());
3401 errs == x
3402 }
3403
3404 #[quickcheck]
3406 fn filterable_partition_consistency(x: Vec<i32>) -> bool {
3407 let p = |i: i32| i % 2 == 0;
3408 let either_bool = |i| if p(i) { Ok(i) } else { Err(i) };
3409
3410 let (not_satisfied, satisfied) = explicit::partition::<VecBrand, _, _, _>(p, x.clone());
3411 let (errs, oks) = explicit::partition_map::<VecBrand, _, _, _, _, _>(either_bool, x);
3412
3413 satisfied == oks && not_satisfied == errs
3414 }
3415
3416 #[quickcheck]
3420 fn witherable_identity(x: Vec<i32>) -> bool {
3421 explicit::wither::<RcFnBrand, VecBrand, OptionBrand, _, _, _, _>(
3422 |i| Some(Some(i)),
3423 x.clone(),
3424 ) == Some(x)
3425 }
3426
3427 #[quickcheck]
3429 fn witherable_wilt_consistency(x: Vec<i32>) -> bool {
3430 let p = |i: i32| Some(if i % 2 == 0 { Ok(i) } else { Err(i) });
3431
3432 let lhs = explicit::wilt::<RcFnBrand, VecBrand, OptionBrand, _, _, _, _, _>(p, x.clone());
3433 let rhs = crate::dispatch::functor::explicit::map::<OptionBrand, _, _, _, _>(
3434 explicit::separate::<VecBrand, _, _, _, _>,
3435 explicit::traverse::<RcFnBrand, VecBrand, _, _, OptionBrand, _, _>(p, x),
3436 );
3437
3438 lhs == rhs
3439 }
3440
3441 #[quickcheck]
3443 fn witherable_wither_consistency(x: Vec<i32>) -> bool {
3444 let p = |i: i32| Some(if i % 2 == 0 { Some(i) } else { None });
3445
3446 let lhs = explicit::wither::<RcFnBrand, VecBrand, OptionBrand, _, _, _, _>(p, x.clone());
3447 let rhs = crate::dispatch::functor::explicit::map::<OptionBrand, _, _, _, _>(
3448 explicit::compact::<VecBrand, _, _, _>,
3449 explicit::traverse::<RcFnBrand, VecBrand, _, _, OptionBrand, _, _>(p, x),
3450 );
3451
3452 lhs == rhs
3453 }
3454
3455 #[quickcheck]
3459 fn alt_associativity(
3460 x: Vec<i32>,
3461 y: Vec<i32>,
3462 z: Vec<i32>,
3463 ) -> bool {
3464 explicit::alt::<VecBrand, _, _, _>(
3465 explicit::alt::<VecBrand, _, _, _>(x.clone(), y.clone()),
3466 z.clone(),
3467 ) == explicit::alt::<VecBrand, _, _, _>(x, explicit::alt::<VecBrand, _, _, _>(y, z))
3468 }
3469
3470 #[quickcheck]
3472 fn alt_distributivity(
3473 x: Vec<i32>,
3474 y: Vec<i32>,
3475 ) -> bool {
3476 let f = |i: i32| i.wrapping_mul(2).wrapping_add(1);
3477 explicit::map::<VecBrand, _, _, _, _>(
3478 f,
3479 explicit::alt::<VecBrand, _, _, _>(x.clone(), y.clone()),
3480 ) == explicit::alt::<VecBrand, _, _, _>(
3481 explicit::map::<VecBrand, _, _, _, _>(f, x),
3482 explicit::map::<VecBrand, _, _, _, _>(f, y),
3483 )
3484 }
3485
3486 #[quickcheck]
3490 fn plus_left_identity(x: Vec<i32>) -> bool {
3491 explicit::alt::<VecBrand, _, _, _>(plus_empty::<VecBrand, i32>(), x.clone()) == x
3492 }
3493
3494 #[quickcheck]
3496 fn plus_right_identity(x: Vec<i32>) -> bool {
3497 explicit::alt::<VecBrand, _, _, _>(x.clone(), plus_empty::<VecBrand, i32>()) == x
3498 }
3499
3500 #[test]
3502 fn plus_annihilation() {
3503 let f = |i: i32| i.wrapping_mul(2);
3504 assert_eq!(
3505 explicit::map::<VecBrand, _, _, _, _>(f, plus_empty::<VecBrand, i32>()),
3506 plus_empty::<VecBrand, i32>(),
3507 );
3508 }
3509
3510 #[quickcheck]
3514 fn compactable_functor_identity(fa: Vec<i32>) -> bool {
3515 explicit::compact::<VecBrand, _, _, _>(explicit::map::<VecBrand, _, _, _, _>(
3516 Some,
3517 fa.clone(),
3518 )) == fa
3519 }
3520
3521 #[test]
3523 fn compactable_plus_annihilation_empty() {
3524 assert_eq!(
3525 explicit::compact::<VecBrand, _, _, _>(plus_empty::<VecBrand, Option<i32>>()),
3526 plus_empty::<VecBrand, i32>(),
3527 );
3528 }
3529
3530 #[quickcheck]
3532 fn compactable_plus_annihilation_map(xs: Vec<i32>) -> bool {
3533 explicit::compact::<VecBrand, _, _, _>(explicit::map::<VecBrand, _, _, _, _>(
3534 |_: i32| None::<i32>,
3535 xs,
3536 )) == plus_empty::<VecBrand, i32>()
3537 }
3538
3539 #[test]
3543 fn compact_empty() {
3544 assert_eq!(
3545 explicit::compact::<VecBrand, i32, _, _>(vec![] as Vec<Option<i32>>),
3546 vec![] as Vec<i32>
3547 );
3548 }
3549
3550 #[test]
3552 fn compact_with_none() {
3553 assert_eq!(
3554 explicit::compact::<VecBrand, i32, _, _>(vec![Some(1), None, Some(2)]),
3555 vec![1, 2]
3556 );
3557 }
3558
3559 #[test]
3561 fn separate_empty() {
3562 let (errs, oks) =
3563 explicit::separate::<VecBrand, i32, i32, _, _>(vec![] as Vec<Result<i32, i32>>);
3564 assert_eq!(oks, vec![] as Vec<i32>);
3565 assert_eq!(errs, vec![] as Vec<i32>);
3566 }
3567
3568 #[test]
3570 fn separate_mixed() {
3571 let (errs, oks) =
3572 explicit::separate::<VecBrand, i32, i32, _, _>(vec![Ok(1), Err(2), Ok(3)]);
3573 assert_eq!(oks, vec![1, 3]);
3574 assert_eq!(errs, vec![2]);
3575 }
3576
3577 #[test]
3579 fn partition_map_empty() {
3580 let (errs, oks) =
3581 explicit::partition_map::<VecBrand, _, _, _, _, _>(|x: i32| Ok::<i32, i32>(x), vec![]);
3582 assert_eq!(oks, vec![] as Vec<i32>);
3583 assert_eq!(errs, vec![] as Vec<i32>);
3584 }
3585
3586 #[test]
3588 fn partition_empty() {
3589 let (not_satisfied, satisfied) =
3590 explicit::partition::<VecBrand, _, _, _>(|x: i32| x > 0, vec![]);
3591 assert_eq!(satisfied, vec![] as Vec<i32>);
3592 assert_eq!(not_satisfied, vec![] as Vec<i32>);
3593 }
3594
3595 #[test]
3597 fn filter_map_empty() {
3598 assert_eq!(
3599 explicit::filter_map::<VecBrand, i32, _, _, _>(|x: i32| Some(x), vec![]),
3600 vec![] as Vec<i32>
3601 );
3602 }
3603
3604 #[test]
3606 fn filter_empty() {
3607 assert_eq!(
3608 explicit::filter::<VecBrand, _, _, _>(|x: i32| x > 0, vec![]),
3609 vec![] as Vec<i32>
3610 );
3611 }
3612
3613 #[test]
3615 fn wilt_empty() {
3616 let res = explicit::wilt::<RcFnBrand, VecBrand, OptionBrand, _, _, _, _, _>(
3617 |x: i32| Some(Ok::<i32, i32>(x)),
3618 vec![],
3619 );
3620 assert_eq!(res, Some((vec![], vec![])));
3621 }
3622
3623 #[test]
3625 fn wither_empty() {
3626 let res = explicit::wither::<RcFnBrand, VecBrand, OptionBrand, _, _, _, _>(
3627 |x: i32| Some(Some(x)),
3628 vec![],
3629 );
3630 assert_eq!(res, Some(vec![]));
3631 }
3632
3633 #[test]
3637 fn test_large_vector_par_fold_map() {
3638 use crate::types::Additive;
3639
3640 let xs: Vec<i32> = (0 .. 100000).collect();
3641 let res = par_fold_map::<VecBrand, _, _>(|x: i32| Additive(x as i64), xs);
3642 assert_eq!(res, Additive(4999950000));
3643 }
3644
3645 #[quickcheck]
3647 fn prop_par_map_equals_map(xs: Vec<i32>) -> bool {
3648 let f = |x: i32| x.wrapping_add(1);
3649 let seq_res = explicit::map::<VecBrand, _, _, _, _>(f, xs.clone());
3650 let par_res = par_map::<VecBrand, _, _>(f, xs);
3651 seq_res == par_res
3652 }
3653
3654 #[quickcheck]
3656 fn prop_par_fold_map_equals_fold_map(xs: Vec<i32>) -> bool {
3657 use crate::types::Additive;
3658
3659 let f = |x: i32| Additive(x as i64);
3660 let seq_res =
3661 crate::functions::explicit::fold_map::<crate::brands::RcFnBrand, VecBrand, _, _, _, _>(
3662 f,
3663 xs.clone(),
3664 );
3665 let par_res = par_fold_map::<VecBrand, _, _>(f, xs);
3666 seq_res == par_res
3667 }
3668
3669 #[quickcheck]
3671 fn prop_par_fold_map_empty_is_empty(xs: Vec<i32>) -> bool {
3672 use crate::types::Additive;
3673
3674 if !xs.is_empty() {
3675 return true;
3676 }
3677 let par_res = par_fold_map::<VecBrand, _, _>(|x: i32| Additive(x as i64), xs);
3678 par_res == empty::<Additive<i64>>()
3679 }
3680
3681 #[quickcheck]
3685 fn monad_rec_identity(x: i32) -> bool {
3686 use {
3687 crate::classes::monad_rec::tail_rec_m,
3688 core::ops::ControlFlow,
3689 };
3690 tail_rec_m::<VecBrand, _, _>(|a| vec![ControlFlow::Break(a)], x) == vec![x]
3691 }
3692
3693 #[test]
3695 fn monad_rec_linear() {
3696 use {
3697 crate::classes::monad_rec::tail_rec_m,
3698 core::ops::ControlFlow,
3699 };
3700 let result = tail_rec_m::<VecBrand, _, _>(
3702 |n| {
3703 if n < 5 { vec![ControlFlow::Continue(n + 1)] } else { vec![ControlFlow::Break(n)] }
3704 },
3705 0,
3706 );
3707 assert_eq!(result, vec![5]);
3708 }
3709
3710 #[test]
3712 fn monad_rec_branching() {
3713 use {
3714 crate::classes::monad_rec::tail_rec_m,
3715 core::ops::ControlFlow,
3716 };
3717 let result = tail_rec_m::<VecBrand, _, _>(
3719 |n: i32| {
3720 if n < 2 {
3721 vec![ControlFlow::Continue(n + 1), ControlFlow::Break(n * 100)]
3722 } else {
3723 vec![ControlFlow::Break(n * 100)]
3724 }
3725 },
3726 0,
3727 );
3728 assert_eq!(result, vec![0, 100, 200]);
3732 }
3733
3734 #[test]
3736 fn monad_rec_empty() {
3737 use {
3738 crate::classes::monad_rec::tail_rec_m,
3739 core::ops::ControlFlow,
3740 };
3741 let result: Vec<i32> =
3742 tail_rec_m::<VecBrand, _, _>(|_n| Vec::<ControlFlow<i32, i32>>::new(), 0);
3743 assert_eq!(result, Vec::<i32>::new());
3744 }
3745
3746 #[test]
3750 fn extend_sum_of_suffixes() {
3751 use crate::classes::extend::extend;
3752 let result = extend::<VecBrand, _, _>(|v: Vec<i32>| v.iter().sum::<i32>(), vec![1, 2, 3]);
3753 assert_eq!(result, vec![6, 5, 3]);
3754 }
3755
3756 #[quickcheck]
3758 fn extend_associativity(w: Vec<i32>) -> bool {
3759 use crate::classes::extend::extend;
3760 let g = |v: Vec<i32>| v.iter().fold(0i32, |a, b| a.wrapping_mul(2).wrapping_add(*b));
3761 let f = |v: Vec<i32>| v.iter().fold(0i32, |a, b| a.wrapping_add(b.wrapping_add(1)));
3762 let lhs = extend::<VecBrand, _, _>(f, extend::<VecBrand, _, _>(g, w.clone()));
3763 let rhs = extend::<VecBrand, _, _>(|w: Vec<i32>| f(extend::<VecBrand, _, _>(g, w)), w);
3764 lhs == rhs
3765 }
3766
3767 #[test]
3769 fn extend_duplicate_suffixes() {
3770 use crate::classes::extend::duplicate;
3771 let result = duplicate::<VecBrand, _>(vec![1, 2, 3]);
3772 assert_eq!(result, vec![vec![1, 2, 3], vec![2, 3], vec![3]]);
3773 }
3774
3775 #[test]
3777 fn extend_empty() {
3778 use crate::classes::extend::extend;
3779 let result =
3780 extend::<VecBrand, _, _>(|v: Vec<i32>| v.iter().sum::<i32>(), Vec::<i32>::new());
3781 assert_eq!(result, Vec::<i32>::new());
3782 }
3783
3784 #[test]
3786 fn extend_singleton() {
3787 use crate::classes::extend::extend;
3788 let result = extend::<VecBrand, _, _>(|v: Vec<i32>| v.iter().sum::<i32>(), vec![42]);
3789 assert_eq!(result, vec![42]);
3790 }
3791
3792 #[quickcheck]
3796 fn ref_functor_identity(v: Vec<i32>) -> bool {
3797 use crate::classes::ref_functor::RefFunctor;
3798 VecBrand::ref_map(|x: &i32| *x, &v) == v
3799 }
3800
3801 #[quickcheck]
3804 fn ref_functor_composition(v: Vec<i32>) -> bool {
3805 use crate::classes::ref_functor::RefFunctor;
3806 let f = |x: &i32| x.wrapping_add(1);
3807 let g = |x: &i32| x.wrapping_mul(2);
3808 VecBrand::ref_map(|x: &i32| g(&f(x)), &v) == VecBrand::ref_map(g, &VecBrand::ref_map(f, &v))
3809 }
3810
3811 #[quickcheck]
3813 fn ref_foldable_additive(v: Vec<i32>) -> bool {
3814 use crate::{
3815 brands::RcFnBrand,
3816 classes::ref_foldable::RefFoldable,
3817 types::Additive,
3818 };
3819 let result: Additive<i32> =
3820 VecBrand::ref_fold_map::<RcFnBrand, _, _>(|x: &i32| Additive(*x), &v);
3821 result.0 == v.iter().copied().fold(0i32, |a, b| a.wrapping_add(b))
3822 }
3823
3824 #[quickcheck]
3827 fn ref_semimonad_left_identity(x: i32) -> bool {
3828 use crate::classes::ref_semimonad::RefSemimonad;
3829 VecBrand::ref_bind(&vec![x], |a: &i32| vec![*a]) == vec![x]
3830 }
3831
3832 #[quickcheck]
3835 fn ref_semimonad_associativity(v: Vec<i32>) -> bool {
3836 use crate::classes::ref_semimonad::RefSemimonad;
3837 let f = |a: &i32| vec![a.wrapping_add(1), a.wrapping_mul(2)];
3838 let g = |b: &i32| vec![b.wrapping_add(10)];
3839 let lhs = VecBrand::ref_bind(&VecBrand::ref_bind(&v, f), g);
3840 let rhs = VecBrand::ref_bind(&v, |a: &i32| VecBrand::ref_bind(&f(a), g));
3841 lhs == rhs
3842 }
3843
3844 #[quickcheck]
3846 fn par_ref_functor_equivalence(v: Vec<i32>) -> bool {
3847 use crate::classes::{
3848 par_ref_functor::ParRefFunctor,
3849 ref_functor::RefFunctor,
3850 };
3851 let f = |x: &i32| x.wrapping_mul(3).wrapping_add(7);
3852 VecBrand::par_ref_map(f, &v) == VecBrand::ref_map(f, &v)
3853 }
3854
3855 #[quickcheck]
3860 fn ref_semimonad_right_identity(v: Vec<i32>) -> bool {
3861 use crate::classes::{
3862 ref_pointed::RefPointed,
3863 ref_semimonad::RefSemimonad,
3864 };
3865 VecBrand::ref_bind(&v, |a: &i32| VecBrand::ref_pure(a)) == v
3866 }
3867
3868 #[quickcheck]
3873 fn ref_lift_identity(v: Vec<i32>) -> bool {
3874 use crate::classes::ref_lift::RefLift;
3875 VecBrand::ref_lift2(|_: &(), b: &i32| *b, &vec![()], &v) == v
3876 }
3877
3878 #[quickcheck]
3883 fn ref_traversable_identity(v: Vec<i32>) -> bool {
3884 use crate::{
3885 classes::ref_traversable::RefTraversable,
3886 types::Identity,
3887 };
3888 let result: Identity<Vec<i32>> =
3889 VecBrand::ref_traverse::<RcFnBrand, _, _, IdentityBrand>(|a: &i32| Identity(*a), &v);
3890 result == Identity(v)
3891 }
3892
3893 #[quickcheck]
3896 fn ref_traversable_consistent_with_traverse(v: Vec<i32>) -> bool {
3897 use crate::classes::{
3898 ref_traversable::RefTraversable,
3899 traversable::Traversable,
3900 };
3901 let ref_result: Option<Vec<String>> = VecBrand::ref_traverse::<RcFnBrand, _, _, OptionBrand>(
3902 |a: &i32| Some(a.to_string()),
3903 &v,
3904 );
3905 let val_result: Option<Vec<String>> =
3906 VecBrand::traverse::<i32, String, OptionBrand>(|a: i32| Some(a.to_string()), v);
3907 ref_result == val_result
3908 }
3909
3910 #[quickcheck]
3914 fn ref_compactable_identity(v: Vec<i32>) -> bool {
3915 let mapped: Vec<Option<i32>> = v.iter().map(|a| Some(*a)).collect();
3916 explicit::compact::<VecBrand, _, _, _>(&mapped) == v
3917 }
3918
3919 #[quickcheck]
3923 fn ref_alt_associativity(
3924 x: Vec<i32>,
3925 y: Vec<i32>,
3926 z: Vec<i32>,
3927 ) -> bool {
3928 explicit::alt::<VecBrand, _, _, _>(&explicit::alt::<VecBrand, _, _, _>(&x, &y), &z)
3929 == explicit::alt::<VecBrand, _, _, _>(&x, &explicit::alt::<VecBrand, _, _, _>(&y, &z))
3930 }
3931
3932 #[quickcheck]
3934 fn ref_alt_distributivity(
3935 x: Vec<i32>,
3936 y: Vec<i32>,
3937 ) -> bool {
3938 let f = |a: &i32| a.wrapping_mul(2);
3939 explicit::map::<VecBrand, _, _, _, _>(f, &explicit::alt::<VecBrand, _, _, _>(&x, &y))
3940 == explicit::alt::<VecBrand, _, _, _>(
3941 &explicit::map::<VecBrand, _, _, _, _>(f, &x),
3942 &explicit::map::<VecBrand, _, _, _, _>(f, &y),
3943 )
3944 }
3945}