Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
ahFunctional.H
Go to the documentation of this file.
1
2/*
3 Aleph_w
4
5 Data structures & Algorithms
6 version 2.0.0b
7 https://github.com/lrleon/Aleph-w
8
9 This file is part of Aleph-w library
10
11 Copyright (c) 2002-2026 Leandro Rabindranath Leon
12
13 Permission is hereby granted, free of charge, to any person obtaining a copy
14 of this software and associated documentation files (the "Software"), to deal
15 in the Software without restriction, including without limitation the rights
16 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17 copies of the Software, and to permit persons to whom the Software is
18 furnished to do so, subject to the following conditions:
19
20 The above copyright notice and this permission notice shall be included in all
21 copies or substantial portions of the Software.
22
23 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 SOFTWARE.
30*/
31
32#ifndef AH_FUNCTIONAL_H
33#define AH_FUNCTIONAL_H
34
60#include <stdexcept>
61#include <utility>
62#include <tuple>
63#include <functional>
64#include <algorithm>
65#include <concepts>
66#include <optional>
67#include <type_traits>
68#include <ah-errors.H>
69#include <ah-ranges.H>
70#include <ah-concepts.H>
71#include <hash-dry.H>
72#include <ah-iterator.H>
73
74namespace Aleph {
78template <typename T>
80{
81 virtual T &get_item() = 0;
82 virtual const T &get_item() const = 0;
83 virtual bool is_found() const noexcept = 0;
84 virtual ~Found_Item() = default;
85};
86
88template <typename T>
89struct None : public Found_Item<T>
90{
91 [[noreturn]] T &get_item() override
92 {
93 ah_invalid_argument() << "Access from None type";
94#if defined(__GNUC__) || defined(__clang__)
95 __builtin_unreachable(); // Satisfies compiler after throw
96#elif defined(_MSC_VER)
97 __assume(0);
98#endif
99 }
100
101 [[noreturn]] const T &get_item() const override
102 {
103 ah_invalid_argument() << "Access from None type";
104#if defined(__GNUC__) || defined(__clang__)
105 __builtin_unreachable();
106#elif defined(_MSC_VER)
107 __assume(0);
108#endif
109 }
110
111 [[nodiscard]] bool is_found() const noexcept override
112 {
113 return false;
114 }
115};
116
118template <typename T>
119struct Some : public Found_Item<T>
120{
122
123 Some(T &i) : item(i) {}
124
125 T &get_item() override
126 {
127 return item;
128 }
129 const T &get_item() const override
130 {
131 return item;
132 }
133 [[nodiscard]] bool is_found() const noexcept override
134 {
135 return true;
136 }
137};
138
150template <typename tgtT, typename srcT>
152{
160 tgtT operator()(const srcT &item) const noexcept(noexcept(static_cast<tgtT>(item)))
161 requires requires(const srcT &x) { static_cast<tgtT>(x); }
162 {
163 return static_cast<tgtT>(item);
164 }
165};
166
172template <typename TR, typename TD>
174{
181 TR operator()(const TR & /*acc */, const TD & /* val */) const
182 noexcept(std::is_nothrow_default_constructible_v<TR>)
183 requires requires { TR(); }
184 {
185 return TR();
186 }
187};
188
193template <typename Key, class Cmp>
194 requires EqualityComparator<Cmp, Key>
195struct DynSetLhash;
196
197namespace functional_detail {
201template <class C>
202using get_it_t = std::decay_t<decltype(std::declval<const C &>().get_it())>;
203
207template <class C>
208using get_curr_t = decltype(std::declval<get_it_t<C> &>().get_curr());
209
213template <class C>
214using get_curr_cref_t = const std::remove_reference_t<get_curr_t<C>> &;
215
217template <typename T, class Eq, typename = void>
218struct Dyn_Set_Lhash_Available : public std::false_type
219{
220};
221
223template <typename T, class Eq>
224struct Dyn_Set_Lhash_Available<T, Eq, std::void_t<decltype(sizeof(DynSetLhash<T, Eq>))>>
225 : public std::true_type
226{
227};
228
229template <typename T, class Eq>
230inline constexpr bool dyn_set_lhash_available = Dyn_Set_Lhash_Available<T, Eq>::value;
231
232template <AlephSequentialIterableContainer Container, class Equal>
233[[nodiscard]] inline bool pairwise_all_unique(const Container &container, Equal &eq)
234{
235 for (auto it1 = container.get_it(); it1.has_curr(); it1.next_ne())
236 {
237 auto it2 = it1;
238 it2.next_ne();
239 for (; it2.has_curr(); it2.next_ne())
240 if (eq(it1.get_curr(), it2.get_curr()))
241 return false;
242 }
243 return true;
244}
245
246template <AlephSequentialIterableContainer Container, class Hash, class Equal>
247 requires std::copy_constructible<typename Container::Item_Type>
248 and requires(const typename Container::Item_Type &v, Hash h, Equal e) {
249 { h(v) } -> std::convertible_to<size_t>;
250 { e(v, v) } -> std::convertible_to<bool>;
251 }
252[[nodiscard]] inline bool all_unique_hash_path(const Container &container, Hash &hash, Equal &eq)
253{
254 using T = typename Container::Item_Type;
255 using Eq_Type = std::remove_cvref_t<Equal>;
256
257 if constexpr (dyn_set_lhash_available<T, Eq_Type>)
258 {
259 using Set_Type = DynSetLhash<T, Eq_Type>;
260 using Hash_Fct = typename Set_Type::Hash_Fct;
261
262 Hash_Fct hash_fct([&hash](const T &value)
263 {
264 return static_cast<size_t>(hash(value));
265 });
266
267 Set_Type seen(17, hash_fct, eq, hash_default_lower_alpha, hash_default_upper_alpha);
268
269 for (auto it = container.get_it(); it.has_curr(); it.next_ne())
270 if (seen.contains_or_insert(it.get_curr()).second)
271 return false;
272 return true;
273 }
274
275 return pairwise_all_unique(container, eq);
276}
277} // namespace functional_detail
278
283template <typename T>
284class DynList;
285
295template <typename T = int, template <typename> class Container = DynList>
296[[nodiscard]] inline Container<T> range(const T start, const T end, const T step = 1)
297{
298 Container<T> ret_val;
299 for (T i = start; i <= end; i += step)
300 ret_val.append(i);
301 return ret_val;
302}
303
314template <typename T = int, template <typename> class Container = DynList>
315[[nodiscard]] inline Container<T> nrange(const T start, const T end, const size_t n)
316{
317 ah_domain_error_if(n == 0) << "nrange: n must be greater than 0";
318
319 Container<T> ret_val;
320 if (n == 1)
321 {
322 ret_val.append(start);
323 return ret_val;
324 }
325
326 const auto step = static_cast<double>(end - start) / (n - 1);
327 for (size_t i = 0; i < n; ++i)
328 ret_val.append(static_cast<T>(start + i * step));
329
330 return ret_val;
331}
332
344template <typename T = int, template <typename> class Container = DynList, class Op>
345[[nodiscard]] inline auto set_range(const T start, const T end, const T step, Op &op)
346 -> Container<std::decay_t<decltype(op(start))>>
347{
348 Container<std::decay_t<decltype(op(start))>> ret_val;
349 for (T i = start; i <= end; i += step)
350 ret_val.append(op(i));
351 return ret_val;
352}
353
355template <typename T = int, template <typename> class Container = DynList, class Op>
356[[nodiscard]] inline auto set_range(const T start, const T end, const T step = 1, Op &&op = Op())
357 -> Container<std::decay_t<decltype(op(start))>>
358{
359 return set_range<T, Container, Op>(start, end, step, op);
360}
361
381template <typename T = int, template <typename> class Container = DynList>
382[[nodiscard]] inline Container<T> contiguous_range(T start, const size_t n)
383{
384 Container<T> ret_val;
385 for (size_t i = 0; i < n; ++i)
386 ret_val.append(start++);
387 return ret_val;
388}
389
397template <typename T = int, template <typename> class Container = DynList>
398[[nodiscard]] Container<T> range(const T n)
399{
400 Container<T> ret_val;
401 for (T i = 0; i < n; ++i)
402 ret_val.append(i);
403 return ret_val;
404}
405
414template <typename T = int>
415[[nodiscard]] inline DynList<T> rep(const size_t n, const T &item)
416{
417 DynList<T> ret_val;
418 for (size_t i = 0; i < n; ++i)
419 ret_val.append(item);
420 return ret_val;
421}
422
424template <typename T = int>
425[[nodiscard]] inline DynList<T> rep(const size_t n, T &&item = T())
426{
427 return rep<T>(n, item);
428}
429
430// ─── In-place fill operations ─────────────────────────────────────────────
431
462template <AlephSequentialContainer C>
463void fill(C &container, const typename C::Item_Type &value)
464{
465 container.mutable_for_each([&value](typename C::Item_Type &item)
466 {
467 item = value;
468 });
469}
470
497template <AlephSequentialContainer C>
498 requires requires(typename C::Item_Type v) { ++v; }
499void iota(C &container, typename C::Item_Type start)
500{
501 container.mutable_for_each([&start](typename C::Item_Type &item)
502 {
503 item = start++;
504 });
505}
506
532template <AlephSequentialContainer C>
533 requires requires(typename C::Item_Type v, typename C::Item_Type s) { v += s; }
534void iota(C &container, typename C::Item_Type start, const typename C::Item_Type step)
535{
536 container.mutable_for_each([&start, &step](typename C::Item_Type &item)
537 {
538 item = start;
539 start += step;
540 });
541}
542
565template <class Container>
566[[nodiscard]]
568{
570 for (auto it = c.get_it(); it.has_curr(); it.next_ne())
571 ret.append(&it.get_curr());
572 return ret;
573}
574
578template <class Container>
579[[nodiscard]]
581{
582 using T = const typename Container::Item_Type *;
583 DynList<T> ret;
584 for (auto it = c.get_it(); it.has_curr(); it.next_ne())
585 ret.append(&it.get_curr());
586 return ret;
587}
588
607template <class Op>
608 requires CallableWith<Op &>
609void each(const size_t start, const size_t end, Op &op)
610{
611 for (size_t i = start; i <= end; ++i)
612 op();
613}
614
616template <class Op>
617 requires CallableWith<Op &>
618void each(size_t start, size_t end, Op &&op)
619{
620 each(start, end, op);
621}
622
624template <class Op>
625 requires CallableWith<Op &>
626void each(const size_t n, Op &op)
627{
628 if (n == 0)
629 return;
630 each(0, n - 1, op);
631}
632
634template <class Op>
635 requires CallableWith<Op &>
636void each(size_t n, Op &&op)
637{
638 each(n, op);
639}
640
648template <class Container>
649[[nodiscard]]
650DynList<typename Container::Item_Type> sublist(const Container &c, size_t pos, const size_t stride)
651{
653 try
654 {
655 for (auto it = c.get_it(pos); it.has_curr(); each(0, stride - 1, [&it]()
656 {
657 it.next();
658 }))
659 ret.append(it.get_curr());
660 }
661 catch (const std::overflow_error &)
662 { /* end of container reached */
663 }
664
665 return ret;
666}
667
669template <class Container>
670[[nodiscard]]
672{
673 return sublist(c, 0, stride);
674}
675
698template <class Container, class Operation>
699inline Container &for_each(Container &container, Operation &operation)
700{
701 container.traverse([&operation](const auto &item)
702 {
703 operation(item);
704 return true;
705 });
706 return container;
707}
708
710template <class Container, class Operation>
711inline const Container &for_each(const Container &container, Operation &operation)
712{
713 container.traverse([&operation](const auto &item)
714 {
715 operation(item);
716 return true;
717 });
718 return container;
719}
720
722template <class Container, class Operation>
723inline Container &for_each(Container &container, Operation &&operation = Operation())
724{
725 return for_each<Container, Operation>(container, operation);
726}
727
729template <class Container, class Operation>
730inline const Container &for_each(const Container &container, Operation &&operation = Operation())
731{
732 return for_each<Container, Operation>(container, operation);
733}
734
762template <class Container, class Operation>
763 requires CallableWith<Operation &, functional_detail::get_curr_t<Container>, std::size_t &>
764inline void enum_for_each(const Container &container, Operation &operation)
765{
766 size_t i = 0;
767 for (auto it = container.get_it(); it.has_curr(); it.next_ne(), ++i)
768 operation(it.get_curr(), i);
769}
770
772template <class Container, class Operation>
773 requires CallableWith<Operation &, functional_detail::get_curr_t<Container>, std::size_t &>
774inline void enum_for_each(const Container &container, Operation &&operation)
775{
776 enum_for_each(container, operation);
777}
778
802template <class Container, class Operation>
803 requires requires(Container &c, Operation &op) { { c.traverse(op) } -> std::convertible_to<bool>; }
804inline bool all(Container &container, Operation &operation)
805{
806 return container.traverse(operation);
807}
808
810template <class Container, class Operation>
811 requires requires(const Container &c, Operation &op) { { c.template traverse<Operation>(op) } -> std::convertible_to<bool>; }
812inline bool all(const Container &container, Operation &operation)
813{
814 return container.template traverse<Operation>(operation);
815}
816
818template <class Container, class Operation>
819 requires requires(Container &c, Operation &op) { { c.traverse(op) } -> std::convertible_to<bool>; }
820inline bool all(Container &container, Operation &&operation = Operation())
821{
822 return all<Container, Operation>(container, operation);
823}
824
826template <class Container, class Operation>
827 requires requires(const Container &c, Operation &op) { { c.template traverse<Operation>(op) } -> std::convertible_to<bool>; }
828inline bool all(const Container &container, Operation &&operation = Operation())
829{
830 return all<Container, Operation>(container, operation);
831}
832
856template <class Container, class Operation>
857inline bool exists(Container &container, Operation &operation)
858{
859 return not container.traverse([&operation](const auto &item)
860 {
861 return not operation(item);
862 });
863}
864
866template <class Container, class Operation>
867inline bool exists(const Container &container, Operation &operation)
868{
869 return not container.traverse([&operation](const auto &item)
870 {
871 return not operation(item);
872 });
873}
874
876template <class Container, class Operation>
877inline bool exists(Container &container, Operation &&operation = Operation())
878{
879 return exists<Container, Operation>(container, operation);
880}
881
883template <class Container, class Operation>
884inline bool exists(const Container &container, Operation &&operation = Operation())
885{
886 return exists<Container, Operation>(container, operation);
887}
888
890template <typename T>
892{
893 bool operator()(const T &) const noexcept
894 {
895 return true;
896 }
897};
898
908template <class Container1,
909 template <typename> class Container2 = Aleph::DynList,
910 class Operation = Dft_Filter_Op<typename Container1::Item_Type>>
911[[nodiscard]] inline Container2<typename Container1::Item_Type> filter(Container1 &container,
912 Operation &operation)
913{
914 Container2<typename Container1::Item_Type> ret_val;
915 container.for_each([&ret_val, &operation](const auto &item)
916 {
917 if (operation(item))
918 ret_val.append(item);
919 });
920 return ret_val;
921}
922
924template <class Container1,
925 template <typename> class Container2 = Aleph::DynList,
926 class Operation = Dft_Filter_Op<typename Container1::Item_Type>>
927[[nodiscard]] inline Container2<typename Container1::Item_Type> filter(const Container1 &container,
928 Operation &operation)
929{
930 Container2<typename Container1::Item_Type> ret_val;
931 container.for_each([&ret_val, &operation](const auto &item)
932 {
933 if (operation(item))
934 ret_val.append(item);
935 });
936 return ret_val;
937}
938
940template <class Container1,
941 template <typename> class Container2 = Aleph::DynList,
942 class Operation = Dft_Filter_Op<typename Container1::Item_Type>>
943[[nodiscard]] inline Container2<typename Container1::Item_Type> filter(Container1 &container,
944 Operation &&operation)
945{
946 return filter<Container1, Container2, Operation>(container, operation);
947}
948
950template <class Container1,
951 template <typename> class Container2 = Aleph::DynList,
952 class Operation = Dft_Filter_Op<typename Container1::Item_Type>>
953[[nodiscard]] inline Container2<typename Container1::Item_Type> filter(const Container1 &container,
954 Operation &&operation)
955{
956 return filter<Container1, Container2, Operation>(container, operation);
957}
958
967template <typename T, class C, class Op>
968 requires requires(DynList<T> &ret, Op &op) { ret.append(op(std::declval<functional_detail::get_curr_t<C>>())); }
969[[nodiscard]] DynList<T> maps(const C &c, Op op)
970{
971 DynList<T> ret;
972 for (auto it = c.get_it(); it.has_curr(); it.next_ne())
973 ret.append(op(it.get_curr()));
974 return ret;
975}
976
983template <typename T, class Container, class Operation>
984[[nodiscard]] inline T foldl(const Container &container, const T &init, Operation operation)
985{
986#if ALEPH_HAS_RANGES
987 if constexpr (std::ranges::range<Container>)
988 return detail::ranges_fold_left(container, init, std::move(operation));
989 else
990#endif
991 {
992 T ret_val = init;
993 for (auto it = container.get_it(); it.has_curr(); it.next_ne())
994 ret_val = operation(ret_val, it.get_curr());
995 return ret_val;
996 }
997}
998
1023template <class Container1, class Container2>
1024[[nodiscard]] inline DynList<std::pair<typename Container1::Item_Type, typename Container2::Item_Type>>
1025zip(const Container1 &a, const Container2 &b)
1026{
1027 typedef typename Container1::Item_Type T1;
1028 typedef typename Container2::Item_Type T2;
1030
1031 auto it1 = a.get_it();
1032 auto it2 = b.get_it();
1033 for (; it1.has_curr() and it2.has_curr(); it1.next_ne(), it2.next_ne())
1034 ret_val.append(std::pair<T1, T2>(it1.get_curr(), it2.get_curr()));
1035
1036 return ret_val;
1037}
1038
1065template <class Container1, class Container2>
1066[[nodiscard]] inline DynList<std::tuple<typename Container1::Item_Type, typename Container2::Item_Type>>
1067tzip(const Container1 &a, const Container2 &b)
1068{
1069 typedef typename Container1::Item_Type T1;
1070 typedef typename Container2::Item_Type T2;
1071 using Tuple = std::tuple<T1, T2>;
1072 DynList<Tuple> ret_val;
1073
1074 auto it1 = a.get_it();
1075 auto it2 = b.get_it();
1076 for (; it1.has_curr() and it2.has_curr(); it1.next_ne(), it2.next_ne())
1077 ret_val.append(Tuple(it1.get_curr(), it2.get_curr()));
1078
1079 return ret_val;
1080}
1081
1108template <class Container1, class Container2>
1109[[nodiscard]] inline DynList<std::pair<typename Container1::Item_Type, typename Container2::Item_Type>>
1110zipEq(const Container1 &a, const Container2 &b)
1111{
1112 typedef typename Container1::Item_Type T1;
1113 typedef typename Container2::Item_Type T2;
1115
1116 auto it1 = a.get_it();
1117 auto it2 = b.get_it();
1118 for (; it1.has_curr() and it2.has_curr(); it1.next_ne(), it2.next_ne())
1119 ret_val.append(std::pair<T1, T2>(it1.get_curr(), it2.get_curr()));
1120
1121 ah_length_error_if(it1.has_curr() or it2.has_curr()) << "Container sizes mismatch";
1122
1123 return ret_val;
1124}
1125
1142template <class Container1, class Container2>
1143[[nodiscard]] inline DynList<std::tuple<typename Container1::Item_Type, typename Container2::Item_Type>>
1144tzipEq(const Container1 &a, const Container2 &b)
1145{
1146 typedef typename Container1::Item_Type T1;
1147 typedef typename Container2::Item_Type T2;
1148 using Tuple = std::tuple<T1, T2>;
1149 DynList<Tuple> ret_val;
1150
1151 auto it1 = a.get_it();
1152 auto it2 = b.get_it();
1153 for (; it1.has_curr() and it2.has_curr(); it1.next_ne(), it2.next_ne())
1154 ret_val.append(Tuple(it1.get_curr(), it2.get_curr()));
1155
1156 ah_length_error_if(it1.has_curr() or it2.has_curr()) << "Container sizes mismatch";
1157
1158 return ret_val;
1159}
1160
1186template <class Container>
1187[[nodiscard]]
1188auto inline enumerate(const Container &c)
1189{
1190 using Item = typename Container::Item_Type;
1191 using Pair = std::pair<Item, size_t>;
1192 DynList<Pair> ret;
1193 size_t i = 0;
1194 c.for_each([&i, &ret](const Item &item)
1195 {
1196 ret.append(Pair(item, i++));
1197 });
1198 return ret;
1199}
1200
1229template <class C1, class C2, class Eq = std::equal_to<typename C1::Item_Type>>
1230[[nodiscard]] inline bool eq(const C1 &c1, const C2 &c2, Eq e = Eq())
1231{
1232 auto it1 = c1.get_it();
1233 auto it2 = c2.get_it();
1234 for (; it1.has_curr() and it2.has_curr(); it1.next_ne(), it2.next_ne())
1235 if (not(e(it1.get_curr(), it2.get_curr())))
1236 return false;
1237
1238 return not(it1.has_curr() or it2.has_curr());
1239}
1240
1242template <typename T>
1243[[nodiscard]] inline bool operator==(const DynList<T> &l1, const DynList<T> &l2)
1244{
1245 return eq(l1, l2);
1246}
1247
1249template <class C1, class C2, class Eq>
1250[[nodiscard]] inline bool containers_eq(const C1 &c1, const C2 &c2, Eq e)
1251{
1252 return eq(c1, c2, e);
1253}
1254
1281template <class C1, class C2, class Eq = std::equal_to<typename C1::Item_Type>>
1282[[nodiscard]] inline std::tuple<bool, size_t, typename C1::Item_Type, typename C2::Item_Type>
1283are_eq(const C1 &c1, const C2 &c2, Eq e = Eq())
1284{
1285 using T = typename C1::Item_Type;
1286 auto it1 = c1.get_it();
1287 auto it2 = c2.get_it();
1288 size_t n = 0;
1289 for (; it1.has_curr() and it2.has_curr(); it1.next_ne(), it2.next_ne(), n++)
1290 {
1291 auto &i1 = it1.get_curr();
1292 auto &i2 = it2.get_curr();
1293 if (not(e(i1, i2)))
1294 return std::make_tuple(false, n, i1, i2);
1295 }
1296
1297 return std::make_tuple(not(it1.has_curr() or it2.has_curr()), n, T(), T());
1298}
1299
1326template <class C1, class C2, class Cmp = std::less<typename C1::Item_Type>>
1327[[nodiscard]] inline bool lesser(const C1 &c1, const C2 &c2, Cmp cmp = Cmp())
1328{
1329 auto it1 = c1.get_it();
1330 auto it2 = c2.get_it();
1331 for (; it1.has_curr() and it2.has_curr(); it1.next_ne(), it2.next_ne())
1332 {
1333 auto &curr1 = it1.get_curr();
1334 auto &curr2 = it2.get_curr();
1335 if (cmp(curr1, curr2))
1336 return true;
1337 if (cmp(curr2, curr1))
1338 return false;
1339 }
1340
1341 if (not it1.has_curr() and not it2.has_curr())
1342 return false;
1343
1344 return it2.has_curr();
1345}
1346
1363template <class C1, class C2, class Eq = std::equal_to<typename C1::Item_Type>>
1364[[nodiscard]] inline bool diff(const C1 &c1, const C2 &c2, Eq e = Eq())
1365{
1366 return not eq(c1, c2, e);
1367}
1368
1393template <class Container>
1394[[nodiscard]] inline auto unzip(const Container &l)
1395{
1396 using T1 = std::decay_t<decltype(l.get_first().first)>;
1397 using T2 = std::decay_t<decltype(l.get_first().second)>;
1400 for (auto it = l.get_it(); it.has_curr(); it.next_ne())
1401 {
1402 auto &curr = it.get_curr();
1403 l1.append(curr.first);
1404 l2.append(curr.second);
1405 }
1406
1407 return std::make_pair(std::move(l1), std::move(l2));
1408}
1409
1436template <template <typename> class Container, typename T1, typename T2>
1437[[nodiscard]] inline std::tuple<Container<T1>, Container<T2>> tunzip(
1438 const Container<std::tuple<T1, T2>> &l)
1439{
1442 for (auto it = l.get_it(); it.has_curr(); it.next_ne())
1443 {
1444 auto &curr = it.get_curr();
1445 l1.append(std::get<0>(curr));
1446 l2.append(std::get<1>(curr));
1447 }
1448
1449 return std::make_tuple(std::move(l1), std::move(l2));
1450}
1451
1458template <class SrcContainer, template <typename> class TgtContainer = Aleph::DynList>
1459[[nodiscard]] inline std::pair<TgtContainer<typename SrcContainer::Item_Type>,
1460 TgtContainer<typename SrcContainer::Item_Type>>
1461partition(const SrcContainer &c,
1462 std::function<bool(const typename SrcContainer::Item_Type &)> operation)
1463{
1464 typedef typename SrcContainer::Item_Type Type;
1465 typedef std::pair<TgtContainer<Type>, TgtContainer<Type>> Pair;
1466
1467 Pair ret_val;
1468 for_each(c, [&ret_val, &operation](const Type &item)
1469 {
1470 if (operation(item))
1471 ret_val.first.append(item);
1472 else
1473 ret_val.second.append(item);
1474 });
1475 return ret_val;
1476}
1477
1479template <class Container>
1481{
1482 using T = typename Container::Key_Type;
1483 using Pair = std::pair<size_t, T>;
1484 size_t i = 0;
1485
1486 return c.Container::template maps<Pair>([&i](const T &d)
1487 {
1488 return Pair(i++, d);
1489 });
1490}
1491
1493template <class Container>
1495 const Container &c)
1496{
1497 using T = typename Container::Key_Type;
1498 using Tuple = std::tuple<size_t, typename Container::Key_Type>;
1499 size_t i = 0;
1500 return c.Container::template maps<std::tuple<size_t, T>>([&i](const T &d)
1501 {
1502 return Tuple(i++, d);
1503 });
1504}
1505
1526template <typename T, template <typename> class Container>
1527[[nodiscard]] inline Container<T> reverse(const Container<T> &l)
1528{
1529 Container<T> ret_val;
1530 l.for_each([&ret_val](const T &item)
1531 {
1532 ret_val.insert(item);
1533 });
1534 return ret_val;
1535}
1536
1558template <class Container>
1559[[nodiscard]]
1560auto gen_seq_list_tuples(const Container &c, size_t n)
1561{
1562 using T = typename Container::Item_Type;
1563 auto it = c.get_it();
1564 DynList<T> l;
1565 for (size_t i = 0; i < n; ++i, it.next())
1566 l.append(it.get_curr());
1567
1568 DynList<DynList<T>> ret;
1569 ret.append(l);
1570 for (; it.has_curr(); it.next_ne())
1571 {
1572 l.remove_first();
1573 l.append(it.get_curr());
1574 ret.append(l);
1575 }
1576
1577 return ret;
1578}
1579
1605template <typename T, template <typename> class Container, class Equal>
1606[[nodiscard]] std::pair<DynList<DynList<T>>, size_t> sequential_groups(const Container<T> &c,
1607 Equal &eq)
1608{
1609 using P = std::pair<DynList<DynList<T>>, size_t>;
1610 if (c.is_empty())
1611 return P(DynList<DynList<T>>(), 0);
1612
1613 DynList<DynList<T>> ret; // this will be the result
1614
1615 DynList<T> *group = &ret.append(DynList<T>()); // creates a first group
1616
1617 auto it = c.get_it(); // put the firstitem into the group
1618 auto curr_item = it.get_curr();
1619 group->append(curr_item);
1620
1621 size_t count = 1; // count the number of groups
1622
1623 for (it.next(); it.has_curr(); it.next_ne())
1624 {
1625 auto &curr = it.get_curr();
1626 if (not eq(curr, curr_item)) // group change?
1627 {
1628 curr_item = curr;
1629 group = &ret.append(DynList<T>()); // create new group and insert it
1630 ++count; // increase the number of groups
1631 }
1632
1633 group->append(curr);
1634 }
1635
1636 return P(ret, count);
1637}
1638
1640template <typename T, template <typename> class Container, class Equal = std::equal_to<T>>
1641[[nodiscard]] std::pair<DynList<DynList<T>>, size_t> sequential_groups(const Container<T> &c,
1642 Equal &&eq = Equal())
1643{
1644 return sequential_groups(c, eq);
1645}
1646
1674template <typename T, template <typename> class Container, class Equal>
1675[[nodiscard]] std::pair<DynList<T>, size_t> unique_sequential(const Container<T> &c, Equal &eq)
1676{
1677 using P = std::pair<DynList<T>, size_t>;
1678 if (c.is_empty())
1679 return P(DynList<T>(), 0);
1680
1681 DynList<T> ret;
1682
1683 auto it = c.get_it(); // put the first item
1684 auto curr_item = it.get_curr();
1685 ret.append(curr_item);
1686
1687 size_t count = 1; // count the number of groups
1688
1689 for (it.next(); it.has_curr(); it.next_ne())
1690 {
1691 auto &curr = it.get_curr();
1692 if (not eq(curr, curr_item)) // group change?
1693 {
1694 curr_item = curr;
1695 ret.append(curr_item);
1696 ++count; // increase the number of groups
1697 }
1698 }
1699
1700 return P(ret, count);
1701}
1702
1704template <typename T, template <typename> class Container, class Equal = std::equal_to<T>>
1705[[nodiscard]] std::pair<DynList<T>, size_t> unique_sequential(const Container<T> &c,
1706 Equal &&eq = Equal())
1707{
1708 return unique_sequential(c, eq);
1709}
1710
1735template <class Itor1, class Itor2 = Itor1>
1737{
1738 Itor1 it1;
1739 Itor2 it2;
1740
1741public:
1743 Pair_Iterator(Itor1 i1, Itor2 i2) : it1(i1), it2(i2) {}
1744
1749 template <class C1, class C2>
1750 requires (not std::same_as<std::remove_cvref_t<C1>, Itor1>)
1751 Pair_Iterator(C1 &c1, C2 &c2) : it1(Aleph::iterator_for(c1)), it2(Aleph::iterator_for(c2))
1752 {}
1753
1757 [[nodiscard]] bool has_curr() const noexcept
1758 {
1759 return it1.has_curr() and it2.has_curr();
1760 }
1761
1763 [[nodiscard]] bool has_curr1() const noexcept
1764 {
1765 return it1.has_curr();
1766 }
1767
1769 [[nodiscard]] bool has_curr2() const noexcept
1770 {
1771 return it2.has_curr();
1772 }
1773
1778 auto get_curr() const
1779 {
1780 return std::make_pair(it1.get_curr(), it2.get_curr());
1781 }
1782
1787 auto get_curr_ne() const noexcept
1788 {
1789 return std::make_pair(it1.get_curr_ne(), it2.get_curr_ne());
1790 }
1791
1795 void next()
1796 {
1797 it1.next();
1798 it2.next();
1799 }
1800
1809 void next_ne() noexcept(noexcept(std::declval<Itor1 &>().next_ne())
1810 and noexcept(std::declval<Itor2 &>().next_ne()))
1811 {
1812 it1.next_ne();
1813 it2.next_ne();
1814 }
1815
1820 [[nodiscard]] bool was_traversed() const noexcept
1821 {
1822 return not(it1.has_curr() or it2.has_curr());
1823 }
1824};
1825
1840template <class C1, class C2>
1841[[nodiscard]] inline auto get_pair_it(C1 &c1, C2 &c2)
1842{
1843 auto i1 = Aleph::iterator_for(c1);
1844 auto i2 = Aleph::iterator_for(c2);
1846}
1847
1849template <class C1, class C2>
1850[[nodiscard]] inline auto get_pair_it(C1 &c1, C2 &c2, const size_t pos)
1851{
1852 auto i1 = Aleph::iterator_for(c1);
1853 auto i2 = Aleph::iterator_for(c2);
1854 for (size_t i = 0; i < pos; ++i)
1855 {
1856 i1.next();
1857 i2.next();
1858 }
1860}
1861
1863namespace functional_detail {
1864
1865/* Whether the insert() or append() call that returned `result` added its
1866 item. A container that may refuse an item (a set, for a key it already
1867 holds) returns a pointer, null when it refuses it; any other result means
1868 that the item was added. */
1869template <class Result>
1870constexpr bool added_item(const Result &result) noexcept
1871{
1872 if constexpr (std::is_pointer_v<Result>)
1873 return result != nullptr;
1874 else
1875 return true;
1876}
1877
1879template <class C, class Item>
1880bool append_one(C &c, Item &&item)
1881{
1882 if constexpr (std::is_void_v<decltype(c.append(std::forward<Item>(item)))>)
1883 {
1884 c.append(std::forward<Item>(item));
1885 return true;
1886 }
1887 else
1888 return added_item(c.append(std::forward<Item>(item)));
1889}
1890
1892template <class C, class Item>
1893bool insert_one(C &c, Item &&item)
1894{
1895 if constexpr (std::is_void_v<decltype(c.insert(std::forward<Item>(item)))>)
1896 {
1897 c.insert(std::forward<Item>(item));
1898 return true;
1899 }
1900 else
1901 return added_item(c.insert(std::forward<Item>(item)));
1902}
1903
1904} // namespace functional_detail
1906
1914template <class C, typename... Args>
1915inline size_t insert_in_container(C &c, Args &&... args)
1916{
1917 size_t n = 0;
1918 ((n += (functional_detail::insert_one(c, std::forward<Args>(args)) ? 1 : 0)), ...);
1919 return n;
1920}
1921
1929template <class C, typename... Args>
1930inline size_t append_in_container(C &c, Args &&... args)
1931{
1932 size_t n = 0;
1933 ((n += (functional_detail::append_one(c, std::forward<Args>(args)) ? 1 : 0)), ...);
1934 return n;
1935}
1936
1943template <class C, typename... Args>
1944[[nodiscard]] C build_container(Args &&... args)
1945{
1946 C c;
1947 append_in_container(c, std::forward<Args>(args)...);
1948 return c;
1949}
1950
1952template <class SrcC, class TgtC>
1953[[nodiscard]] TgtC assign_container(const SrcC &srcc)
1954{
1955 TgtC ret;
1956 for (auto it = srcc.get_it(); it.has_curr(); it.next_ne())
1957 ret.append(it.get_curr());
1958
1959 return ret;
1960}
1961
1963template <typename T, typename... Args>
1964[[nodiscard]] DynList<T> build_dynlist(Args &&... args)
1965{
1966 return build_container<DynList<T>>(std::forward<Args>(args)...);
1967}
1968
1970template <class C>
1971inline void remove_from_container(C &, size_t &)
1972{}
1973
1974template <class C, typename T, typename... Args>
1975inline void remove_from_container(C &c, size_t &n, const T &item, Args &...args)
1976{
1977 c.remove(item);
1978 ++n;
1979 remove_from_container(c, n, args...);
1980}
1982
1986template <class C, typename... Args>
1987inline size_t remove_from_container(C &c, Args... args)
1988{
1989 size_t n = 0;
1990 remove_from_container(c, n, args...);
1991 return n;
1992}
1993
1994// These functions are defined in tpl_dynSetHash.H
1995
1997template <typename T, template <typename> class Container>
1998[[nodiscard]] inline DynList<T> join(const Container<T> &c1, const Container<T> &c2);
1999
2001template <typename T, template <typename> class Container>
2002[[nodiscard]] inline DynList<T> intercept(const Container<T> &c1, const Container<T> &c2);
2003
2005template <typename T, template <typename> class Container>
2006[[nodiscard]] inline DynList<T> unique(const Container<T> &c);
2007
2009template <typename T, template <typename> class Container>
2010[[nodiscard]] inline DynList<T> repeated(const Container<T> &c);
2011
2013template <typename T, template <typename> class Container>
2014[[nodiscard]] inline DynList<std::pair<T, size_t>> repeated_with_index(const Container<T> &c);
2015
2036template <typename T, template <typename> class C1, template <typename> class C2>
2037[[nodiscard]] DynList<T> flatten(const C2<C1<T>> &c)
2038{
2039 DynList<T> ret;
2040 for (auto it_c = c.get_it(); it_c.has_curr(); it_c.next_ne())
2041 {
2042 const auto &curr_c = it_c.get_curr();
2043 for (auto it = curr_c.get_it(); it.has_curr(); it.next_ne())
2044 ret.append(it.get_curr());
2045 }
2046 return ret;
2047}
2048
2060template <typename T, template <typename> class C1, template <typename> class C2, template <typename> class C3>
2061[[nodiscard]] DynList<T> flatten(const C3<C2<C1<T>>> &c)
2062{
2063 DynList<T> ret;
2064 for (auto it = c.get_it(); it.has_curr(); it.next_ne())
2065 ret.append(flatten(it.get_curr()));
2066 return ret;
2067}
2068
2080template <typename T,
2081 template <typename> class C1,
2082 template <typename> class C2,
2083 template <typename> class C3,
2084 template <typename> class C4>
2085[[nodiscard]] DynList<T> flatten(const C4<C3<C2<C1<T>>>> &c)
2086{
2087 DynList<T> ret;
2088 for (auto it = c.get_it(); it.has_curr(); it.next_ne())
2089 ret.append(flatten(it.get_curr()));
2090 return ret;
2091}
2092
2104template <typename T,
2105 template <typename> class C1,
2106 template <typename> class C2,
2107 template <typename> class C3,
2108 template <typename> class C4,
2109 template <typename> class C5>
2110[[nodiscard]] DynList<T> flatten(const C5<C4<C3<C2<C1<T>>>>> &c)
2111{
2112 DynList<T> ret;
2113 for (auto it = c.get_it(); it.has_curr(); it.next_ne())
2114 ret.append(flatten(it.get_curr()));
2115 return ret;
2116}
2117
2137template <typename T>
2138[[nodiscard]] inline bool is_inside(const T &val, const DynList<T> &values)
2139{
2140 for (const auto &v : values)
2141 if (val == v)
2142 return true;
2143 return false;
2144}
2145
2163template <typename T>
2164[[nodiscard]] inline bool is_equal(const T &val)
2165{
2166 (void) val;
2167 return false;
2168}
2169
2176template <typename T, typename U, typename... Args>
2177[[nodiscard]] inline bool is_equal(const T &val, const U &rhs, const Args &...args)
2178{
2179 return (val == rhs) or is_equal(val, args...);
2180}
2181
2188template <class Container, class Operation>
2189[[nodiscard]] inline bool none(const Container &container, Operation &operation)
2190{
2191 return not exists(container, operation);
2192}
2193
2195template <class Container, class Operation>
2196[[nodiscard]] inline bool none(const Container &container, Operation &&operation = Operation())
2197{
2198 return none<Container, Operation>(container, operation);
2199}
2200
2228template <class Container, class Pred>
2229[[nodiscard]] inline typename Container::Item_Type *find_ptr(Container &container, Pred &pred)
2230{
2231 typename Container::Item_Type *result = nullptr;
2232 // Not a generic lambda: with `auto &` the constant traverse() overload,
2233 // which hands out `const Item_Type &`, would instantiate this body.
2234 container.traverse([&result, &pred](typename Container::Item_Type &item)
2235 {
2236 if (pred(item))
2237 {
2238 result = &item;
2239 return false;
2240 }
2241 return true;
2242 });
2243 return result;
2244}
2245
2247template <class Container, class Pred>
2248[[nodiscard]] inline const typename Container::Item_Type *find_ptr(const Container &container,
2249 Pred &pred)
2250{
2251 const typename Container::Item_Type *result = nullptr;
2252 container.traverse([&result, &pred](const auto &item)
2253 {
2254 if (pred(item))
2255 {
2256 result = &item;
2257 return false;
2258 }
2259 return true;
2260 });
2261 return result;
2262}
2263
2265template <class Container, class Pred>
2266[[nodiscard]] inline typename Container::Item_Type *find_ptr(Container &container, Pred &&pred)
2267{
2268 return find_ptr<Container, Pred>(container, pred);
2269}
2270
2272template <class Container, class Pred>
2273[[nodiscard]] inline const typename Container::Item_Type *find_ptr(const Container &container,
2274 Pred &&pred)
2275{
2276 return find_ptr<Container, Pred>(container, pred);
2277}
2278
2301template <class Container, class Pred>
2302[[nodiscard]] inline std::optional<typename Container::Item_Type> find_opt(const Container &container,
2303 Pred &pred)
2304{
2305 std::optional<typename Container::Item_Type> result;
2306 container.traverse([&result, &pred](const auto &item)
2307 {
2308 if (pred(item))
2309 {
2310 result = item;
2311 return false;
2312 }
2313 return true;
2314 });
2315 return result;
2316}
2317
2319template <class Container, class Pred>
2320[[nodiscard]] inline std::optional<typename Container::Item_Type> find_opt(const Container &container,
2321 Pred &&pred)
2322{
2323 return find_opt<Container, Pred>(container, pred);
2324}
2325
2335template <typename T, class Container, class Operation>
2336 requires requires(T &acc, Operation &op, T &x) { acc = op(x, acc); }
2337[[nodiscard]] inline T foldr(const Container &container, const T &init, Operation operation)
2338{
2339 DynList<T> reversed;
2340 for (auto it = container.get_it(); it.has_curr(); it.next_ne())
2341 reversed.insert(it.get_curr());
2342
2343 T ret_val = init;
2344 for (auto it = reversed.get_it(); it.has_curr(); it.next_ne())
2345 ret_val = operation(it.get_curr(), ret_val);
2346 return ret_val;
2347}
2348
2356template <class Container, typename T = typename Container::Item_Type>
2357[[nodiscard]] inline T sum(const Container &container, const T &init = T{})
2358{
2359#if ALEPH_HAS_RANGES
2360 if constexpr (std::ranges::range<Container>)
2361 return detail::ranges_fold_left(container, init, std::plus<>{});
2362 else
2363#endif
2364 {
2365 T result = init;
2366 for (auto it = container.get_it(); it.has_curr(); it.next_ne())
2367 result = result + it.get_curr();
2368 return result;
2369 }
2370}
2371
2379template <class Container, typename T = typename Container::Item_Type>
2380[[nodiscard]] inline T product(const Container &container, const T &init = T{1})
2381{
2382#if ALEPH_HAS_RANGES
2383 if constexpr (std::ranges::range<Container>)
2384 return detail::ranges_fold_left(container, init, std::multiplies<>{});
2385 else
2386#endif
2387 {
2388 T result = init;
2389 for (auto it = container.get_it(); it.has_curr(); it.next_ne())
2390 result = result * it.get_curr();
2391 return result;
2392 }
2393}
2394
2402template <class C1, class C2>
2403[[nodiscard]] inline DynList<typename C1::Item_Type> concat(const C1 &c1, const C2 &c2)
2404{
2406 for (auto it = c1.get_it(); it.has_curr(); it.next_ne())
2407 result.append(it.get_curr());
2408 for (auto it = c2.get_it(); it.has_curr(); it.next_ne())
2409 result.append(it.get_curr());
2410 return result;
2411}
2412
2420template <class Container, class Pred>
2421 requires PredicateWith<Pred &, functional_detail::get_curr_cref_t<Container>>
2423{
2425 for (auto it = c.get_it(); it.has_curr(); it.next_ne())
2426 {
2427 const auto &item = it.get_curr();
2428 if (not pred(item))
2429 break;
2430 result.append(item);
2431 }
2432 return result;
2433}
2434
2442template <class Container, class Pred>
2443 requires PredicateWith<Pred &, functional_detail::get_curr_cref_t<Container>>
2445{
2447 bool dropping = true;
2448 for (auto it = c.get_it(); it.has_curr(); it.next_ne())
2449 {
2450 const auto &item = it.get_curr();
2451 if (dropping and pred(item))
2452 continue;
2453 dropping = false;
2454 result.append(item);
2455 }
2456 return result;
2457}
2458
2468template <class Container, class Op>
2469[[nodiscard]] inline auto flat_map(const Container &container, Op op)
2471{
2472 using ResultItemType =
2473 typename std::decay_t<decltype(op(std::declval<typename Container::Item_Type>()))>::Item_Type;
2475 for (auto it = container.get_it(); it.has_curr(); it.next_ne())
2476 {
2477 auto sub = op(it.get_curr());
2478 for (auto sit = sub.get_it(); sit.has_curr(); sit.next_ne())
2479 result.append(sit.get_curr());
2480 }
2481 return result;
2482}
2483
2493template <typename T, class Container>
2494[[nodiscard]] inline DynList<T> scanl_sum(const Container &container, const T &init)
2495{
2496 DynList<T> result;
2497 T acc = init;
2498 result.append(acc);
2499 for (auto it = container.get_it(); it.has_curr(); it.next_ne())
2500 {
2501 acc = acc + it.get_curr();
2502 result.append(acc);
2503 }
2504 return result;
2505}
2506
2517template <typename T, class Container, class Op>
2518 requires requires(T &acc, Op &op) { acc = op(acc, std::declval<functional_detail::get_curr_t<Container>>()); }
2519[[nodiscard]] inline DynList<T> scanl(const Container &container, const T &init, Op op)
2520{
2521 DynList<T> result;
2522 T acc = init;
2523 result.append(acc);
2524 for (auto it = container.get_it(); it.has_curr(); it.next_ne())
2525 {
2526 acc = op(acc, it.get_curr());
2527 result.append(acc);
2528 }
2529 return result;
2530}
2531
2539template <class Container, class Cmp = std::less<typename Container::Item_Type>>
2540 requires PredicateWith<Cmp &, functional_detail::get_curr_cref_t<Container>, const typename Container::Item_Type &>
2541[[nodiscard]] inline const typename Container::Item_Type *min_ptr(const Container &container,
2542 Cmp cmp = Cmp())
2543{
2544 auto it = container.get_it();
2545 if (not it.has_curr())
2546 return nullptr;
2547
2548 const typename Container::Item_Type *min_elem = &it.get_curr();
2549 for (it.next_ne(); it.has_curr(); it.next_ne())
2550 {
2551 const auto &curr = it.get_curr();
2552 if (cmp(curr, *min_elem))
2553 min_elem = &curr;
2554 }
2555 return min_elem;
2556}
2557
2565template <class Container, class Cmp = std::less<typename Container::Item_Type>>
2566 requires PredicateWith<Cmp &, const typename Container::Item_Type &, functional_detail::get_curr_cref_t<Container>>
2567[[nodiscard]] inline const typename Container::Item_Type *max_ptr(const Container &container,
2568 Cmp cmp = Cmp())
2569{
2570 auto it = container.get_it();
2571 if (not it.has_curr())
2572 return nullptr;
2573
2574 const typename Container::Item_Type *max_elem = &it.get_curr();
2575 for (it.next_ne(); it.has_curr(); it.next_ne())
2576 {
2577 const auto &curr = it.get_curr();
2578 if (cmp(*max_elem, curr))
2579 max_elem = &curr;
2580 }
2581 return max_elem;
2582}
2583
2591template <class Container, class Cmp = std::less<typename Container::Item_Type>>
2592 requires PredicateWith<Cmp &, functional_detail::get_curr_cref_t<Container>, const typename Container::Item_Type &> and
2593 PredicateWith<Cmp &, const typename Container::Item_Type &, functional_detail::get_curr_cref_t<Container>>
2594[[nodiscard]] inline std::pair<const typename Container::Item_Type *, const typename Container::Item_Type *>
2595minmax_ptr(const Container &container, Cmp cmp = Cmp())
2596{
2597 using T = typename Container::Item_Type;
2598 auto it = container.get_it();
2599 if (not it.has_curr())
2600 return {nullptr, nullptr};
2601
2602 const T *min_elem = &it.get_curr();
2603 const T *max_elem = min_elem;
2604 for (it.next_ne(); it.has_curr(); it.next_ne())
2605 {
2606 const auto &curr = it.get_curr();
2607 if (cmp(curr, *min_elem))
2608 min_elem = &curr;
2609 if (cmp(*max_elem, curr))
2610 max_elem = &curr;
2611 }
2612 return {min_elem, max_elem};
2613}
2614
2622template <class Container, class Pred>
2623 requires PredicateWith<Pred &, functional_detail::get_curr_t<Container>>
2624[[nodiscard]] inline size_t count_if(const Container &container, Pred pred)
2625{
2626 size_t count = 0;
2627 for (auto it = container.get_it(); it.has_curr(); it.next_ne())
2628 if (pred(it.get_curr()))
2629 ++count;
2630 return count;
2631}
2632
2649template <AlephSequentialIterableContainer Container, class Equal>
2650[[nodiscard]] inline bool all_unique(const Container &container, Equal &eq)
2651{
2652 using T = typename Container::Item_Type;
2653 using Eq = std::remove_cvref_t<Equal>;
2654
2655 if constexpr (std::is_same_v<Eq, std::equal_to<T>> and std::copy_constructible<T>
2656 and requires(const T &v) {
2657 { std::hash<T>{}(v) } -> std::convertible_to<size_t>;
2658 })
2659 {
2660 auto hash = [](const T &value) -> size_t
2661 {
2662 return std::hash<T>{}(value);
2663 };
2664 return functional_detail::all_unique_hash_path(container, hash, eq);
2665 }
2666
2667 return functional_detail::pairwise_all_unique(container, eq);
2668}
2669
2684template <AlephSequentialIterableContainer Container,
2685 class Equal = std::equal_to<typename Container::Item_Type>>
2686[[nodiscard]] inline bool all_unique(const Container &container, Equal &&eq = Equal())
2687{
2688 return all_unique<Container, Equal>(container, eq);
2689}
2690
2706template <AlephSequentialIterableContainer Container, class Hash, class Equal>
2707 requires std::copy_constructible<typename Container::Item_Type>
2708 and requires(const typename Container::Item_Type &v, Hash h, Equal e) {
2709 { h(v) } -> std::convertible_to<size_t>;
2710 { e(v, v) } -> std::convertible_to<bool>;
2711 }
2712[[nodiscard]] inline bool all_unique(const Container &container, Hash &hash, Equal &eq)
2713{
2714 return functional_detail::all_unique_hash_path(container, hash, eq);
2715}
2716
2717template <AlephSequentialIterableContainer Container, class Hash, class Equal>
2718 requires std::copy_constructible<typename Container::Item_Type>
2719 and requires(const typename Container::Item_Type &v, Hash h, Equal e) {
2720 { h(v) } -> std::convertible_to<size_t>;
2721 { e(v, v) } -> std::convertible_to<bool>;
2722 }
2724[[nodiscard]] inline bool all_unique(const Container &container, Hash &&hash, Equal &&eq)
2725{
2726 using Hash_Type = std::remove_reference_t<Hash>;
2727 using Eq_Type = std::remove_reference_t<Equal>;
2728
2729 Hash_Type hash_obj = std::forward<Hash>(hash);
2730 Eq_Type eq_obj = std::forward<Equal>(eq);
2731 return all_unique(container, hash_obj, eq_obj);
2732}
2733
2741template <class Container>
2742[[nodiscard]] inline bool contains(const Container &container,
2743 const typename Container::Item_Type &value)
2744{
2745 for (auto it = container.get_it(); it.has_curr(); it.next_ne())
2746 if (it.get_curr() == value)
2747 return true;
2748 return false;
2749}
2750
2759template <class Container>
2761 const Container &container)
2762{
2763 using T = typename Container::Item_Type;
2764 using Tuple = std::tuple<size_t, T>;
2765 DynList<Tuple> result;
2766 size_t i = 0;
2767 for (auto it = container.get_it(); it.has_curr(); it.next_ne(), ++i)
2768 result.append(Tuple(i, it.get_curr()));
2769 return result;
2770}
2771
2806template <class Container1, class Container2>
2807[[nodiscard]] inline DynList<std::pair<typename Container1::Item_Type, typename Container2::Item_Type>>
2808zip_longest(const Container1 &a,
2809 const Container2 &b,
2810 const typename Container1::Item_Type &fill_a = typename Container1::Item_Type(),
2811 const typename Container2::Item_Type &fill_b = typename Container2::Item_Type())
2812{
2813 using T1 = typename Container1::Item_Type;
2814 using T2 = typename Container2::Item_Type;
2816
2817 auto it1 = a.get_it();
2818 auto it2 = b.get_it();
2819
2820 // Process while both have elements
2821 while (it1.has_curr() and it2.has_curr())
2822 {
2823 ret_val.append(std::pair<T1, T2>(it1.get_curr(), it2.get_curr()));
2824 it1.next_ne();
2825 it2.next_ne();
2826 }
2827
2828 // Process remaining elements from the first container
2829 while (it1.has_curr())
2830 {
2831 ret_val.append(std::pair<T1, T2>(it1.get_curr(), fill_b));
2832 it1.next_ne();
2833 }
2834
2835 // Process remaining elements from the second container
2836 while (it2.has_curr())
2837 {
2838 ret_val.append(std::pair<T1, T2>(fill_a, it2.get_curr()));
2839 it2.next_ne();
2840 }
2841
2842 return ret_val;
2843}
2844
2876template <class Container1, class Container2>
2877[[nodiscard]] inline DynList<std::tuple<typename Container1::Item_Type, typename Container2::Item_Type>>
2878tzip_longest(const Container1 &a,
2879 const Container2 &b,
2880 const typename Container1::Item_Type &fill_a = typename Container1::Item_Type(),
2881 const typename Container2::Item_Type &fill_b = typename Container2::Item_Type())
2882{
2883 using T1 = typename Container1::Item_Type;
2884 using T2 = typename Container2::Item_Type;
2885 using Tuple = std::tuple<T1, T2>;
2886 DynList<Tuple> ret_val;
2887
2888 auto it1 = a.get_it();
2889 auto it2 = b.get_it();
2890
2891 while (it1.has_curr() and it2.has_curr())
2892 {
2893 ret_val.append(Tuple(it1.get_curr(), it2.get_curr()));
2894 it1.next_ne();
2895 it2.next_ne();
2896 }
2897
2898 while (it1.has_curr())
2899 {
2900 ret_val.append(Tuple(it1.get_curr(), fill_b));
2901 it1.next_ne();
2902 }
2903
2904 while (it2.has_curr())
2905 {
2906 ret_val.append(Tuple(fill_a, it2.get_curr()));
2907 it2.next_ne();
2908 }
2909
2910 return ret_val;
2911}
2912
2948template <class Container1, class Container2>
2949[[nodiscard]] inline DynList<std::pair<std::optional<typename Container1::Item_Type>,
2950 std::optional<typename Container2::Item_Type>>>
2951zip_longest_opt(const Container1 &a, const Container2 &b)
2952{
2953 using T1 = typename Container1::Item_Type;
2954 using T2 = typename Container2::Item_Type;
2955 using Opt1 = std::optional<T1>;
2956 using Opt2 = std::optional<T2>;
2958
2959 auto it1 = a.get_it();
2960 auto it2 = b.get_it();
2961
2962 while (it1.has_curr() and it2.has_curr())
2963 {
2964 ret_val.append(std::make_pair(Opt1(it1.get_curr()), Opt2(it2.get_curr())));
2965 it1.next_ne();
2966 it2.next_ne();
2967 }
2968
2969 while (it1.has_curr())
2970 {
2971 ret_val.append(std::make_pair(Opt1(it1.get_curr()), std::nullopt));
2972 it1.next_ne();
2973 }
2974
2975 while (it2.has_curr())
2976 {
2977 ret_val.append(std::make_pair(std::nullopt, Opt2(it2.get_curr())));
2978 it2.next_ne();
2979 }
2980
2981 return ret_val;
2982}
2983
3032template <typename T, template <typename> class Container, class KeyFunc>
3033[[nodiscard]]
3035 KeyFunc key_func)
3036{
3037 using Key = std::invoke_result_t<KeyFunc, const T &>;
3038 using Group = DynList<T>;
3039 using Result = DynList<std::pair<Key, Group>>;
3040
3041 Result ret;
3042 if (c.is_empty())
3043 return ret;
3044
3045 auto it = c.get_it();
3046 Key curr_key = key_func(it.get_curr());
3047 Group *curr_group = &ret.append(std::make_pair(curr_key, Group())).second;
3048 curr_group->append(it.get_curr());
3049
3050 for (it.next_ne(); it.has_curr(); it.next_ne())
3051 {
3052 const auto &item = it.get_curr();
3053 Key new_key = key_func(item);
3054
3055 if (new_key != curr_key)
3056 {
3057 curr_key = new_key;
3058 curr_group = &ret.append(std::make_pair(curr_key, Group())).second;
3059 }
3060
3061 curr_group->append(item);
3062 }
3063
3064 return ret;
3065}
3066
3098template <typename T, template <typename> class Container, class KeyFunc, class KeyEqual>
3099[[nodiscard]]
3100DynList<std::pair<std::invoke_result_t<KeyFunc, const T &>, DynList<T>>>
3101group_by_eq(const Container<T> &c, KeyFunc key_func, KeyEqual key_equal)
3102{
3103 using Key = std::invoke_result_t<KeyFunc, const T &>;
3104 using Group = DynList<T>;
3105 using Result = DynList<std::pair<Key, Group>>;
3106
3107 Result ret;
3108 if (c.is_empty())
3109 return ret;
3110
3111 auto it = c.get_it();
3112 Key curr_key = key_func(it.get_curr());
3113 Group *curr_group = &ret.append(std::make_pair(curr_key, Group())).second;
3114 curr_group->append(it.get_curr());
3115
3116 for (it.next_ne(); it.has_curr(); it.next_ne())
3117 {
3118 const auto &item = it.get_curr();
3119 Key new_key = key_func(item);
3120
3121 if (not key_equal(new_key, curr_key))
3122 {
3123 curr_key = new_key;
3124 curr_group = &ret.append(std::make_pair(curr_key, Group())).second;
3125 }
3126
3127 curr_group->append(item);
3128 }
3129
3130 return ret;
3131}
3132
3170template <typename T, template <typename> class Container, class KeyFunc, class Reducer>
3171[[nodiscard]]
3172auto group_by_reduce(const Container<T> &c, KeyFunc key_func, Reducer reducer) -> DynList<
3173 std::pair<std::invoke_result_t<KeyFunc, const T &>, std::invoke_result_t<Reducer, const DynList<T> &>>>
3174{
3175 using Key = std::invoke_result_t<KeyFunc, const T &>;
3176 using ReducedType = std::invoke_result_t<Reducer, const DynList<T> &>;
3178
3179 auto groups = group_by(c, key_func);
3180 Result ret;
3181
3182 for (auto it = groups.get_it(); it.has_curr(); it.next_ne())
3183 {
3184 auto &[key, group] = it.get_curr();
3185 ret.append(std::make_pair(key, reducer(group)));
3186 }
3187
3188 return ret;
3189}
3190
3191} // end namespace Aleph
3192
3193#endif // AH_FUNCTIONAL_H
C++20 concepts hub: comparison, BST policy, and Aleph container concepts.
Exception handling system with formatted messages for Aleph-w.
#define ah_length_error_if(C)
Throws std::length_error if condition holds.
Definition ah-errors.H:846
#define ah_invalid_argument()
Throws std::invalid_argument unconditionally.
Definition ah-errors.H:819
#define ah_domain_error_if(C)
Throws std::domain_error if condition holds.
Definition ah-errors.H:670
STL-compatible iterator adapters for Aleph containers.
C++20 Ranges support and adaptors for Aleph-w containers.
long double h
Definition btreepic.C:154
size_t size_t int32_t value
Definition ca-c-api.h:116
Doubly-linked list (defined in tpl_dynList.H).
Definition htlist.H:1231
T & get_first()
Return the first item of the list.
Definition htlist.H:1548
T & append(const T &item)
Definition htlist.H:1362
T remove_first()
See remove().
Definition htlist.H:1473
Iterator that zips two other iterators.
auto get_curr_ne() const noexcept
Get current pair (no bounds check).
void next_ne() noexcept(noexcept(std::declval< Itor1 & >().next_ne()) and noexcept(std::declval< Itor2 & >().next_ne()))
Advance both iterators (no bounds check).
bool has_curr1() const noexcept
Check if first iterator has current element.
Pair_Iterator(Itor1 i1, Itor2 i2)
Construct from two iterators.
bool has_curr() const noexcept
Check if both iterators have current elements.
bool was_traversed() const noexcept
Check if both iterators were completely traversed.
Pair_Iterator(C1 &c1, C2 &c2)
Construct from two containers.
bool has_curr2() const noexcept
Check if second iterator has current element.
void next()
Advance both iterators (bounds-checked).
auto get_curr() const
Get current pair (bounds-checked).
void for_each(Operation &operation) const
Traverse all the container and performs an operation on each element.
Definition ah-dry.H:1475
auto get_it()
Return a properly initialized iterator positioned at the first item on the container.
Definition ah-dry.H:663
pair< size_t, string > P
int cmp(const __gmp_expr< T, U > &expr1, const __gmp_expr< V, W > &expr2)
Definition gmpfrxx.h:4196
Common hash table utilities and base classes.
Freq_Node * pred
Predecessor node in level-order traversal.
constexpr T ranges_fold_left(Container &&c, T init, BinaryOp &&op)
Fallback fold_left using range-based for loop.
Definition ah-ranges.H:921
decltype(std::declval< get_it_t< C > & >().get_curr()) get_curr_t
Type of it.get_curr() on a get_it_t<C> lvalue.
const std::remove_reference_t< get_curr_t< C > > & get_curr_cref_t
Type of const auto &item = it.get_curr().
bool pairwise_all_unique(const Container &container, Equal &eq)
bool all_unique_hash_path(const Container &container, Hash &hash, Equal &eq)
constexpr bool dyn_set_lhash_available
std::decay_t< decltype(std::declval< const C & >().get_it())> get_it_t
Type of auto it = c.get_it() for a const C &c.
Main namespace for Aleph-w library functions.
std::pair< DynList< T >, size_t > unique_sequential(const Container< T > &c, Equal &eq)
Extract unique consecutive items.
std::tuple< bool, size_t, typename C1::Item_Type, typename C2::Item_Type > are_eq(const C1 &c1, const C2 &c2, Eq e=Eq())
Detailed equality check returning mismatch position and values.
DynList< T > flatten(const C2< C1< T > > &c)
Flatten a nested container of one level.
void each(const size_t start, const size_t end, Op &op)
Execute an operation repeatedly over a range of indices.
Container< T > nrange(const T start, const T end, const size_t n)
Generate exactly n values evenly spaced between [start, end].
auto group_by_reduce(const Container< T > &c, KeyFunc key_func, Reducer reducer) -> DynList< std::pair< std::invoke_result_t< KeyFunc, const T & >, std::invoke_result_t< Reducer, const DynList< T > & > > >
Group consecutive elements and apply a reducer to each group.
DynList< std::pair< std::optional< typename Container1::Item_Type >, std::optional< typename Container2::Item_Type > > > zip_longest_opt(const Container1 &a, const Container2 &b)
Zip two containers using optionals for missing values.
auto unzip(const Container &l)
Separate a list of pairs into two lists.
void reverse(Itor beg, Itor end)
Reverse elements in a range.
Definition ahAlgo.H:1094
bool eq(const C1 &c1, const C2 &c2, Eq e=Eq())
Check equality of two containers using a predicate.
Itor unique(Itor __first, Itor __last, BinaryPredicate __binary_pred=BinaryPredicate())
Remove consecutive duplicates in place.
Definition ahAlgo.H:1058
T Item_Type
Type of elements from the first container.
Definition ah-zip.H:161
bool operator==(const DynList< T > &l1, const DynList< T > &l2)
Equality operator for DynList.
auto set_range(const T start, const T end, const T step, Op &op) -> Container< std::decay_t< decltype(op(start))> >
Generate a range [start, end] and apply an operation to each value.
DynList< std::pair< typename Container1::Item_Type, typename Container2::Item_Type > > zipEq(const Container1 &a, const Container2 &b)
Zip two containers; throw if lengths differ.
DynList< T > intercept(const Container< T > &c1, const Container< T > &c2)
Return intersection of two containers as a DynList.
void enum_for_each(const Container &container, Operation &operation)
Apply an operation to each element and its index.
std::pair< TgtContainer< typename SrcContainer::Item_Type >, TgtContainer< typename SrcContainer::Item_Type > > partition(const SrcContainer &c, std::function< bool(const typename SrcContainer::Item_Type &)> operation)
Partition a container into two based on a predicate.
bool containers_eq(const C1 &c1, const C2 &c2, Eq e)
See eq.
bool all_unique(const Container &container, Equal &eq)
Check if all elements in a container are unique using a comparator.
DynList< std::pair< T, size_t > > repeated_with_index(const Container< T > &c)
Return repeated elements paired with their occurrence count.
T foldr(const Container &container, const T &init, Operation operation)
Right fold (reduce).
Container2< typename Container1::Item_Type > filter(Container1 &container, Operation &operation)
Filter elements that satisfy operation.
size_t remove_from_container(C &c, Args... args)
Remove multiple items from a container.
bool is_inside(const T &val, const DynList< T > &values)
Check if a value is present in a list.
std::string concat(const Args &...args)
Concatenate multiple arguments into a single std::string.
DynList< T > repeated(const Container< T > &c)
Return elements that appear more than once in the container.
const float hash_default_upper_alpha
Definition hash-dry.C:40
const Container::Item_Type * max_ptr(const Container &container, Cmp cmp=Cmp())
Find the maximum element in a container.
DynList< std::pair< typename Container1::Item_Type, typename Container2::Item_Type > > zip(const Container1 &a, const Container2 &b)
Zip two containers into a list of pairs.
bool all(Container &container, Operation &operation)
Return true if all elements satisfy a predicate.
void fill(Itor beg, const Itor &end, const T &value)
Fill a range with a value.
Definition ahAlgo.H:707
auto enumerate(const Container &c)
Return pairs of (element, index).
bool is_equal(const T &val)
Variadic check for equality against multiple values.
T foldl(const Container &container, const T &init, Operation operation)
Classic left fold (reduce).
std::decay_t< typename HeadC::Item_Type > T
Definition ah-zip.H:152
bool exists(Container &container, Operation &operation)
Return true if at least one element satisfies a predicate.
auto gen_seq_list_tuples(const Container &c, size_t n)
Generate all sequential tuples (sliding windows) of size n.
bool contains(const std::string_view &str, const std::string_view &substr)
Check if substr appears inside str.
void iota(C &container, typename C::Item_Type start)
Fill all elements of a container with unit-step sequential values.
std::optional< typename Container::Item_Type > find_opt(const Container &container, Pred &pred)
Find the first element satisfying pred (safe version).
DynList< T > rep(const size_t n, const T &item)
Create a sequence of repeated items.
auto flat_map(const Container &container, Op op) -> DynList< typename std::decay_t< decltype(op(std::declval< typename Container::Item_Type >()))>::Item_Type >
Apply operation and flatten results (flatMap/concatMap).
auto get_curr() const
Return the current tuple (bounds-checked).
Definition ah-zip.H:192
DynList< std::tuple< typename Container1::Item_Type, typename Container2::Item_Type > > tzip(const Container1 &a, const Container2 &b)
Zip two containers into a list of tuples.
and
Check uniqueness with explicit hash + equality functors.
T product(const Container &container, const T &init=T{1})
Compute product of all elements.
bool diff(const C1 &c1, const C2 &c2, Eq e=Eq())
Check if two containers differ.
and PredicateWith< Cmp &, const typename Container::Item_Type &, functional_detail::get_curr_cref_t< Container > > std::pair< const typename Container::Item_Type *, const typename Container::Item_Type * > minmax_ptr(const Container &container, Cmp cmp=Cmp())
Find both min and max elements in a single pass.
DynList< typename Container::Item_Type * > pointers_list(Container &c)
Create a list of pointers to items in a container.
DynList< std::pair< size_t, typename Container::Key_Type > > indexes(const Container &c)
Return pairs of (index, key).
bool lesser(const C1 &c1, const C2 &c2, Cmp cmp=Cmp())
Lexicographical comparison between two containers.
DynList< typename Container::Item_Type > take_while(const Container &c, Pred pred)
Return elements while predicate is true (take_while).
size_t append_in_container(C &c, Args &&... args)
Append multiple items into a container.
TgtC assign_container(const SrcC &srcc)
Convert one container type to another.
DynList< std::tuple< size_t, typename Container::Item_Type > > enumerate_tuple(const Container &container)
Zip containers with an index (enumerate with zip).
DynList< std::tuple< typename Container1::Item_Type, typename Container2::Item_Type > > tzipEq(const Container1 &a, const Container2 &b)
Zip two containers into tuples; throw if lengths differ.
Operation for_each(Itor beg, const Itor &end, Operation op)
Apply an operation to each element in a range.
Definition ahAlgo.H:76
C build_container(Args &&... args)
Build a container with the given items.
std::pair< DynList< DynList< T > >, size_t > sequential_groups(const Container< T > &c, Equal &eq)
Group consecutive equal elements together.
DynList< std::tuple< size_t, typename Container::Key_Type > > tindexes(const Container &c)
Return tuples of (index, key).
Itor::difference_type count_if(Itor beg, const Itor &end, Operation op)
Count elements satisfying a predicate.
Definition ahAlgo.H:100
DynList< T > scanl_sum(const Container &container, const T &init)
Compute running sums (scanl with addition).
DynList< std::tuple< typename Container1::Item_Type, typename Container2::Item_Type > > tzip_longest(const Container1 &a, const Container2 &b, const typename Container1::Item_Type &fill_a=typename Container1::Item_Type(), const typename Container2::Item_Type &fill_b=typename Container2::Item_Type())
Zip two containers into tuples, padding the shorter one.
DynList< T > scanl(const Container &container, const T &init, Op op)
Prefix scan with custom operation.
DynList< std::pair< std::invoke_result_t< KeyFunc, const T & >, DynList< T > > > group_by_eq(const Container< T > &c, KeyFunc key_func, KeyEqual key_equal)
Group consecutive elements by a key function with custom equality.
DynList< std::pair< typename Container1::Item_Type, typename Container2::Item_Type > > zip_longest(const Container1 &a, const Container2 &b, const typename Container1::Item_Type &fill_a=typename Container1::Item_Type(), const typename Container2::Item_Type &fill_b=typename Container2::Item_Type())
Zip two containers, padding the shorter one with a fill value.
std::ostream & join(const C &c, const std::string &sep, std::ostream &out)
Join elements of an Aleph-style container into a stream.
DynList< typename Container::Item_Type > sublist(const Container &c, size_t pos, const size_t stride)
Extract a sublist using a stride.
Container::Item_Type * find_ptr(Container &container, Pred &pred)
Find the first element satisfying pred.
Container< T > range(const T start, const T end, const T step=1)
Generate a range of values [start, end] with a given step.
DynList< std::pair< std::invoke_result_t< KeyFunc, const T & >, DynList< T > > > group_by(const Container< T > &c, KeyFunc key_func)
Group consecutive elements by a key function.
Container< T > contiguous_range(T start, const size_t n)
Generate n contiguous values starting from start.
DynList< T > build_dynlist(Args &&... args)
Build a DynList with the given items; an rvalue is moved.
const float hash_default_lower_alpha
Definition hash-dry.C:38
bool none(const Container &container, Operation &operation)
Return true if no element satisfies operation.
auto get_pair_it(C1 &c1, C2 &c2)
Create a Pair_Iterator for two containers.
auto iterator_for(C &c)
Iterator on c positioned on its first item: the container's own iterator on a modifiable container.
static std::atomic< bool > init
Definition hash-fct.C:54
DynList< typename Container::Item_Type > drop_while(const Container &c, Pred pred)
Skip elements while predicate is true (drop_while).
const Container::Item_Type * min_ptr(const Container &container, Cmp cmp=Cmp())
Find the minimum element in a container.
size_t insert_in_container(C &c, Args &&... args)
Insert multiple items into a container.
@ Tuple
Tuple type such as (Int, Bool).
std::tuple< Container< T1 >, Container< T2 > > tunzip(const Container< std::tuple< T1, T2 > > &l)
Separate a list of tuples into two containers.
Itor::difference_type count(const Itor &beg, const Itor &end, const T &value)
Count elements equal to a value.
Definition ahAlgo.H:127
DynList< T > maps(const C &c, Op op)
Classic map operation.
T sum(const Container &container, const T &init=T{})
Compute sum of all elements.
STL namespace.
Default filter operation (always true).
bool operator()(const T &) const noexcept
Default folding operation (returns default-constructed accumulator).
TR operator()(const TR &, const TD &) const noexcept(std::is_nothrow_default_constructible_v< TR >)
Builds an accumulator by default, whatever it is given.
Default mapping operation: the conversion of the item, which is its copy when the two types are the s...
tgtT operator()(const srcT &item) const noexcept(noexcept(static_cast< tgtT >(item)))
Converts an item to the type of the result.
Hash-based dynamic set (defined in tpl_dynSetHash.H).
Abstract base class for optional-like results.
virtual bool is_found() const noexcept=0
virtual T & get_item()=0
virtual const T & get_item() const =0
Represents a missing value.
const T & get_item() const override
T & get_item() override
bool is_found() const noexcept override
Represents a found value (stored by reference).
const T & get_item() const override
bool is_found() const noexcept override
T & get_item() override
DynList< int > l1
DynList< int > l2
DynList< int > l