170#include <tclap/CmdLine.h>
179using namespace Aleph;
185template <
typename Container>
188 cout << label <<
": [";
190 c.for_each([&first](
const auto& x) {
191 if (not first) cout <<
", ";
198template <
typename T1,
typename T2>
201 cout << label <<
": [";
203 c.for_each([&first](
const auto& p) {
204 if (not first) cout <<
", ";
205 cout <<
"(" << p.first <<
", " << p.second <<
")";
213 cout <<
"\n" << string(60,
'=') <<
"\n";
214 cout <<
" " << title <<
"\n";
215 cout << string(60,
'=') <<
"\n\n";
220 cout <<
"\n--- " << title <<
" ---\n";
233 auto r1 =
range(1, 10);
234 auto r2 =
range(0, 20, 5);
235 auto r3 =
range(10, 1, -2);
240 cout <<
" Note: range() only works with positive steps\n";
249 auto nr1 =
nrange(0.0, 1.0, 5);
250 auto nr2 =
nrange(0.0, 10.0, 11);
252 cout <<
"nrange(0.0, 1.0, 5): [";
254 nr1.for_each([&first](
double x) {
255 if (not first) cout <<
", ";
256 cout << fixed << setprecision(2) << x;
261 cout <<
"nrange(0.0, 10.0, 11): [";
263 nr2.for_each([&first](
double x) {
264 if (not first) cout <<
", ";
265 cout << fixed << setprecision(1) << x;
279 auto rep1 =
rep(5, 42);
280 auto rep2 = rep<string>(3,
"hello");
297 cout <<
"Elements: ";
298 nums.
for_each([](
int x) { cout << x <<
" "; });
303 nums.
for_each([](
int x) { cout << (x * x) <<
" "; });
309 cout <<
"Indexed list:\n";
311 cout <<
" [" << i <<
"] " << name << endl;
316 cout <<
"Print until finding 3: ";
321 cout <<
"(stopped)" << endl;
341 auto is_even = [](
int x) {
return x % 2 == 0; };
342 auto is_positive = [](
int x) {
return x > 0; };
343 auto is_less_than_20 = [](
int x) {
return x < 20; };
345 cout <<
"All even in nums? " << (nums.
all(
is_even) ?
"yes" :
"no") << endl;
346 cout <<
"All even in mixed? " << (mixed.
all(
is_even) ?
"yes" :
"no") << endl;
347 cout <<
"All positive in nums? " << (nums.
all(is_positive) ?
"yes" :
"no") << endl;
348 cout <<
"All < 20 in nums? " << (nums.
all(is_less_than_20) ?
"yes" :
"no") << endl;
349 cout <<
"All in empty list? " << (empty_list.
all(
is_even) ?
"yes (vacuous truth)" :
"no") << endl;
353 auto is_five = [](
int x) {
return x == 5; };
354 auto is_greater_than_7 = [](
int x) {
return x > 7; };
356 cout <<
"Exists 5 in nums? " << (nums.
exists(is_five) ?
"yes" :
"no") << endl;
357 cout <<
"Exists 5 in mixed? " << (mixed.
exists(is_five) ?
"yes" :
"no") << endl;
358 cout <<
"Exists > 7 in nums? " << (nums.
exists(is_greater_than_7) ?
"yes" :
"no") << endl;
362 auto is_negative = [](
int x) {
return x < 0; };
363 auto is_odd = [](
int x) {
return x % 2 != 0; };
365 cout <<
"None negative in nums? " << (
none(nums, is_negative) ?
"yes" :
"no") << endl;
366 cout <<
"None odd in nums? " << (
none(nums,
is_odd) ?
"yes" :
"no") << endl;
367 cout <<
"None odd in mixed? " << (
none(mixed,
is_odd) ?
"yes" :
"no") << endl;
371 cout <<
"nums contains 6? " << (
contains(nums, 6) ?
"yes" :
"no") << endl;
372 cout <<
"nums contains 7? " << (
contains(nums, 7) ?
"yes" :
"no") << endl;
388 auto evens = nums.
filter([](
int x) {
return x % 2 == 0; });
389 auto greater_than_5 = nums.
filter([](
int x) {
return x > 5; });
391 if (x < 2)
return false;
392 for (
int i = 2; i * i <= x; ++i)
393 if (x % i == 0)
return false;
403 auto squares = nums.template maps<int>([](
int x) {
return x * x; });
404 auto doubled = nums.template maps<int>([](
int x) {
return x * 2; });
405 auto as_strings = nums.template maps<string>([](
int x) {
415 auto even_squares = nums
416 .
filter([](
int x) {
return x % 2 == 0; })
417 .
template maps<int>([](
int x) {
return x * x; });
428 auto expanded =
flat_map(small, [](
int x) {
440 cout <<
"Nested: [[1,2], [3,4,5], [6]]\n";
441 auto flattened =
flatten(nested);
460 int sum_result = nums.template foldl<int>(0, [](
int acc,
int x) {
463 cout <<
"Sum (foldl): " << sum_result << endl;
466 int prod_result = nums.template foldl<int>(1, [](
int acc,
int x) {
469 cout <<
"Product (foldl): " << prod_result << endl;
472 int max_result = nums.template foldl<int>(nums.
get_first(), [](
int acc,
int x) {
473 return x > acc ? x : acc;
475 cout <<
"Max (foldl): " << max_result << endl;
479 string concat = words.template foldl<string>(
"", [](
const string& acc,
const string& s) {
482 cout <<
"Concatenation: \"" <<
concat <<
"\"" << endl;
489 string left = seq.template foldl<string>(
"", [](
const string& acc,
int x) {
490 return "(" + acc +
"+" +
to_string(x) +
")";
492 cout <<
"foldl with +: " << left << endl;
493 cout <<
" Evaluation: ((\"\" + 1) + 2) + 3" << endl;
497 string right = rev_seq.template foldl<string>(
"", [](
const string& acc,
int x) {
498 return "(" +
to_string(x) +
"+" + acc +
")";
500 cout <<
"Right-to-left fold: " << right << endl;
501 cout <<
" Evaluation: 1 + (2 + (3 + \"\"))" << endl;
505 cout <<
"sum({1,2,3,4,5}) = " <<
sum(nums) << endl;
506 cout <<
"product({1,2,3,4,5}) = " <<
product(nums) << endl;
509 cout <<
"sum({1.5, 2.0, 3.5}) = " <<
sum(doubles) << endl;
530 auto zipped =
zip(nums, letters);
533 auto zipped_short =
zip(nums, values);
534 cout <<
"zip(nums, values): [";
536 zipped_short.for_each([&first](
const auto& p) {
537 if (not first) cout <<
", ";
538 cout <<
"(" << p.first <<
", " << p.second <<
")";
541 cout <<
"] (stops at shorter)\n";
545 cout <<
"Iterating with ZipIterator:\n";
546 for (
ZipIterator it(nums, letters); it.has_curr(); it.next())
548 auto [n,
l] = it.get_curr();
549 cout <<
" " << n <<
" -> " <<
l << endl;
557 pairs.
append({3,
"three"});
559 auto [first_list, second_list] =
unzip(pairs);
568 auto sums =
zip(a, b).template maps<int>([](
const auto& p) {
569 return p.first + p.second;
571 auto products =
zip(a, b).template maps<int>([](
const auto& p) {
572 return p.first * p.second;
592 auto [evens, odds] =
partition(nums, [](
int x) {
return x % 2 == 0; });
610 auto by_mod3 =
group_by(nums, [](
int x) {
return x % 3; });
611 cout <<
"Grouped by x % 3:\n";
612 by_mod3.for_each([](
const auto& group) {
613 cout <<
" Key " << group.first <<
": [";
615 group.second.for_each([&first](
int x) {
616 if (not first) cout <<
", ";
624 DynList<string> words = {
"hi",
"hello",
"bye",
"ok",
"world",
"no",
"yes"};
627 auto by_length =
group_by(words, [](
const string& s) {
return s.
length(); });
628 cout <<
"Grouped by length:\n";
629 by_length.for_each([](
const auto& group) {
630 cout <<
" Length " << group.first <<
": [";
632 group.second.for_each([&first](
const string& s) {
633 if (not first) cout <<
", ";
634 cout <<
"\"" << s <<
"\"";
654 double total =
sum(data);
660 .template maps<double>([
mean](
double x) {
return (x -
mean) * (x -
mean); })
661 .
template foldl<double>(0.0, [](
double acc,
double x) {
return acc + x; }) /
count;
665 cout <<
"Count: " <<
count << endl;
666 cout <<
"Sum: " << fixed << setprecision(2) << total << endl;
667 cout <<
"Mean: " <<
mean << endl;
668 cout <<
"Variance: " <<
variance << endl;
669 cout <<
"Std Dev: " <<
stddev << endl;
677 auto processed = text
678 .template maps<string>([](
const string& s) {
680 for (
char c : s) lower +=
tolower(c);
683 .
filter([](
const string& s) {
return s.length() > 2; });
696 row.for_each([](
int x) { cout << x <<
" "; });
702 auto fibonacci =
range(10).template foldl<DynList<int>>(
705 size_t n = acc.
size();
708 acc.for_each([&](
int x) {
709 if (idx == n - 2 or idx == n - 1)
740 cout <<
"eq(a, b)? " << (
eq(a, b) ?
"yes" :
"no") << endl;
741 cout <<
"eq(a, c)? " << (
eq(a, c) ?
"yes" :
"no") <<
" (different lengths)" << endl;
742 cout <<
"eq(a, d)? " << (
eq(a, d) ?
"yes" :
"no") <<
" (different element)" << endl;
746 cout <<
"diff(a, b)? " << (
diff(a, b) ?
"yes" :
"no") << endl;
747 cout <<
"diff(a, d)? " << (
diff(a, d) ?
"yes" :
"no") << endl;
759 cout <<
"lesser(x, y)? " << (
lesser(x,
y) ?
"yes" :
"no") <<
" (3 < 4)" << endl;
760 cout <<
"lesser(y, x)? " << (
lesser(
y, x) ?
"yes" :
"no") << endl;
761 cout <<
"lesser(z, x)? " << (
lesser(z, x) ?
"yes" :
"no") <<
" (prefix)" << endl;
768int main(
int argc,
char* argv[])
773 "Comprehensive functional programming example for Aleph-w.\n"
774 "Demonstrates range generation, iteration, predicates, transformation,\n"
775 "folding, zipping, grouping, and more.",
779 TCLAP::ValueArg<string> sectionArg(
781 "Run only specific section: ranges, iteration, predicates, transform, "
782 "fold, zip, group, practical, compare, or 'all'",
783 false,
"all",
"section",
cmd
786 cmd.parse(argc, argv);
788 string section = sectionArg.getValue();
791 cout <<
"============================================================\n";
792 cout <<
" ALEPH-W FUNCTIONAL PROGRAMMING EXAMPLE\n";
793 cout <<
"============================================================\n";
822 cout <<
"\n" << string(60,
'=') <<
"\n";
823 cout <<
"Functional programming demo completed!\n";
824 cout << string(60,
'=') <<
"\n\n";
828 catch (TCLAP::ArgException& e)
830 cerr <<
"Error: " << e.error() <<
" for argument " << e.argId() << endl;
835 cerr <<
"Error: " << e.what() << endl;
Functional programming utilities for Aleph-w containers.
High-level sorting functions for Aleph containers.
Doubly-linked list (defined in tpl_dynList.H).
T & get_first()
Return the first item of the list.
T & append(const T &item)
size_t size() const noexcept
Return the number of items of the list, in constant time.
size_t length() const noexcept(Aleph::dry_detail::const_traversal_is_noexcept< Container, T >)
Count the number of elements of a container.
bool exists(Operation &op) const
Test for existence in the container of an element satisfying a criterion.
Aleph::DynList< T > filter(Operation &operation) const
Filter the elements of a container according to a matching criterion.
bool all(Operation &operation) const
Check if all the elements of the container satisfy a condition.
void for_each(Operation &operation) const
Traverse all the container and performs an operation on each element.
Iterator that traverses multiple Aleph containers in lockstep.
void print_subsection(const string &title)
void print_section(const string &title)
void print_pairs(const string &label, const DynList< pair< T1, T2 > > &c)
void print_container(const string &label, const Container &c)
void demo_transformation()
__gmp_expr< T, __gmp_unary_expr< __gmp_expr< T, U >, __gmp_sqrt_function > > sqrt(const __gmp_expr< T, U > &expr)
Singly linked list implementations with head-tail access.
Main namespace for Aleph-w library functions.
std::string tolower(const char *str)
Convert a C std::string to lower-case.
DynList< T > flatten(const C2< C1< T > > &c)
Flatten a nested container of one level.
Container< T > nrange(const T start, const T end, const size_t n)
Generate exactly n values evenly spaced between [start, end].
auto unzip(const Container &l)
Separate a list of pairs into two lists.
void reverse(Itor beg, Itor end)
Reverse elements in a range.
bool eq(const C1 &c1, const C2 &c2, Eq e=Eq())
Check equality of two containers using a predicate.
void enum_for_each(const Container &container, Operation &operation)
Apply an operation to each element and its index.
auto variance(const Container &data, bool population=false) -> std::decay_t< decltype(*std::begin(data))>
Compute variance using Welford's numerically stable algorithm.
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.
Container2< typename Container1::Item_Type > filter(Container1 &container, Operation &operation)
Filter elements that satisfy operation.
static void suffix(Node *root, DynList< Node * > &acc)
std::string concat(const Args &...args)
Concatenate multiple arguments into a single std::string.
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 contains(const std::string_view &str, const std::string_view &substr)
Check if substr appears inside str.
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).
static void prefix(Node *root, DynList< Node * > &acc)
auto stddev(const Container &data, bool population=false) -> std::decay_t< decltype(*std::begin(data))>
Compute standard deviation.
auto mean(const Container &data) -> std::decay_t< decltype(*std::begin(data))>
Compute the arithmetic mean.
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.
std::pair< First, Second > pair
Alias to std::pair kept for backwards compatibility.
bool is_even(const long n)
Return true if n is even.
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).
std::string to_string(const time_t t, const std::string &format)
Format a time_t value into a string using format.
void next()
Advance all underlying iterators (bounds-checked).
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.
bool none(const Container &container, Operation &operation)
Return true if no element satisfies operation.
DynList< typename Container::Item_Type > drop_while(const Container &c, Pred pred)
Skip elements while predicate is true (drop_while).
Itor::difference_type count(const Itor &beg, const Itor &end, const T &value)
Count elements equal to a value.
T sum(const Container &container, const T &init=T{})
Compute sum of all elements.
static void section(const string &title)
bool traverse(Operation &operation) noexcept(traverse_is_noexcept< Operation, typename Aleph::concepts_detail::traverse_arg< Container, Operation >::type, Container & >())
Traverse the container via its iterator and performs a conditioned operation on each item.
Lazy and scalable dynamic array implementation.
Dynamic doubly linked list implementation.