Aleph-w 3.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
functional_example.C File Reference

Comprehensive example of functional programming in Aleph-w. More...

#include <iostream>
#include <iomanip>
#include <string>
#include <cmath>
#include <tclap/CmdLine.h>
#include <tpl_dynArray.H>
#include <tpl_dynDlist.H>
#include <htlist.H>
#include <ahFunctional.H>
#include <ahSort.H>
Include dependency graph for functional_example.C:

Go to the source code of this file.

Functions

template<typename Container >
void print_container (const string &label, const Container &c)
 
template<typename T1 , typename T2 >
void print_pairs (const string &label, const DynList< pair< T1, T2 > > &c)
 
void print_section (const string &title)
 
void print_subsection (const string &title)
 
void demo_ranges ()
 
void demo_iteration ()
 
void demo_predicates ()
 
void demo_transformation ()
 
void demo_folding ()
 
void demo_zipping ()
 
void demo_grouping ()
 
void demo_practical ()
 
void demo_comparison ()
 
int main (int argc, char *argv[])
 

Detailed Description

Comprehensive example of functional programming in Aleph-w.

This program demonstrates all major functional programming features available in Aleph-w through ahFunctional.H. Functional programming provides a declarative, composable approach to data processing that is often more readable and less error-prone than imperative loops.

What is Functional Programming?

Functional programming emphasizes:

  • Immutability: Operations don't modify original data
  • Composability: Small functions combine into larger operations
  • Declarative: Describe what you want, not how to do it
  • Higher-order functions: Functions that take/return functions

Benefits:

  • More readable code
  • Easier to reason about
  • Better for parallelization
  • Less error-prone (no mutation bugs)

Features Demonstrated

Range Generation

Create sequences of values:

  • **range(start, end, step)**: Generate numeric ranges (like Python's range)
  • **nrange(start, end, n)**: Generate n evenly spaced values
  • **contiguous_range(start, n)**: Generate n consecutive values
  • **rep(n, value)**: Repeat a value n times

Example: range(1, 10, 2) → [1, 3, 5, 7, 9]

Iteration

Apply operations to containers:

  • **for_each(container, op)**: Apply function to each element
  • **enum_for_each(container, op)**: Apply with index (i, element)
  • **traverse(container, op)**: Conditional traversal (can stop early)

Predicates

Test conditions on containers:

  • **all(container, pred)**: All elements satisfy predicate?
  • **exists(container, pred)**: At least one satisfies?
  • **none(container, pred)**: No element satisfies?
  • **contains(container, value)**: Value exists in container?

Transformation

Transform containers into new containers:

  • **maps<T>(container, op)**: Transform each element (like std::transform)
  • **filter(container, pred)**: Keep elements satisfying predicate
  • **flat_map(container, op)**: Map and flatten nested results
  • **reverse(container)**: Reverse order of elements
  • **flatten(container)**: Flatten nested containers

Folding/Reduction

Combine elements into a single value:

  • **foldl(container, init, op)**: Left fold (reduce from left)
  • **foldr(container, init, op)**: Right fold (reduce from right)
  • **sum(container)**: Sum all numeric elements
  • **product(container)**: Multiply all numeric elements

Example: foldl([1,2,3], 0, +) → 6 (sum)

Zipping

Combine multiple containers element-wise:

  • **zip(c1, c2)**: Create pairs from two containers
  • **zipEq(c1, c2)**: Zip with length equality check
  • **unzip(container)**: Split pairs back into two containers
  • **zip_longest(c1, c2, d1, d2)**: Zip with defaults for shorter container

Example: ‘zip([1,2,3], ['a’,'b','c'])‘ → [(1,'a’), (2,'b'), (3,'c')]

Grouping

Organize elements by criteria:

  • **group_by(container, key_func)**: Group elements by key function
  • **partition(container, pred)**: Split into two groups (true/false)
  • **take_while(container, pred)**: Take prefix satisfying predicate
  • **drop_while(container, pred)**: Drop prefix satisfying predicate

Functional Style Example

Imperative style (traditional):

vector<int> result;
for (int x : data) {
if (x > 0) {
result.push_back(x * 2);
}
}

Functional style (Aleph-w):

auto result = filter(data, [](int x) { return x > 0; })
.maps<int>([](int x) { return x * 2; });
Container2< typename Container1::Item_Type > filter(Container1 &container, Operation &operation)
Filter elements that satisfy operation.

More concise, readable, and composable!

Composition and Pipelining

Functional operations compose naturally:

// Process data through pipeline
auto result = data
| filter(is_positive) // Keep positive numbers
| maps(square) // Square them
| filter(is_even) // Keep even results
| sum(); // Sum everything
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.

Comparison with STL

Feature STL Aleph-w Functional
Transform std::transform maps()
Filter Manual loop filter()
Reduce std::accumulate foldl()
Composition Manual chaining Natural composition
Immutability Modifies input Returns new container

Performance Considerations

  • Immutability: Creates new containers (memory overhead)
  • Composition: Can be optimized by compiler
  • Lazy evaluation: Some operations can be deferred (see ranges_example.C)
  • Parallelization: Functional code easier to parallelize

Usage Examples

# Run all demonstrations
./functional_example
# Run specific section
./functional_example -s ranges # Range generation
./functional_example -s iteration # Iteration helpers
./functional_example -s predicates # Predicates
./functional_example -s transform # Mapping/filtering
./functional_example -s fold # Folding operations
./functional_example -s zip # Zipping operations
./functional_example -s group # Grouping/partitioning
./functional_example -s practical # Practical examples
./functional_example -s compare # Comparisons / equality
See also
ahFunctional.H Main functional programming header
ranges_example.C C++20 Ranges (lazy evaluation)
uni_functional_example.C Unified functional (works with STL too)
ah-dry.H Container mixins for functional methods
Author
Leandro Rabindranath León
Date
2024

Definition in file functional_example.C.

Function Documentation

◆ demo_comparison()

void demo_comparison ( )

◆ demo_folding()

◆ demo_grouping()

◆ demo_iteration()

◆ demo_practical()

◆ demo_predicates()

◆ demo_ranges()

◆ demo_transformation()

◆ demo_zipping()

◆ main()

◆ print_container()

template<typename Container >
void print_container ( const string &  label,
const Container c 
)

◆ print_pairs()

template<typename T1 , typename T2 >
void print_pairs ( const string &  label,
const DynList< pair< T1, T2 > > &  c 
)

Definition at line 199 of file functional_example.C.

References FunctionalMethods< Container, T >::for_each(), and Aleph::maps().

Referenced by demo_zipping().

◆ print_section()

void print_section ( const string &  title)

◆ print_subsection()

void print_subsection ( const string &  title)