Functional Programming with C++

Functional programming is about treating functions as attributes that can be passed as arguments and executed inside called function. With help of generic programming this can lead to highly optimized software.

Example:

int numbers[] = {5,7,13,122};
const int size = sizeof(numbers)/sizeof(numbers[0]);
int sum;

// Calculates a sum of integers in array (C style)
sum = 0;
for(int i=0; i < size; ++i)
  sum += numbers[i]; 
cout << "Sum (C): " << sum << "\n";

// Calculates a sum of integers in array (STL style)  
sum = std::accumulate(numbers, numbers+size, 0);
cout << "Sum (STL): " << sum << "\n";

// Calculates a sum of integers in array (functional STL style)
// std::plus can be replaced by std::minus or own function / functor (class with operator "()")
sum = std::accumulate(numbers, numbers+size, 0, std::plus<int>());
cout << "Sum (STL plus): " << sum << "\n";

// Calculates a sum of integers in array (C++11 style)  
sum = 0;
for (int n: numbers) 
  sum += n;
cout << "Sum (C++11): " << sum << "\n";

// Calculates a sum of integers in array (functional C++11 lambdas)
sum = 0;
std::for_each(std::begin(numbers), std::end(numbers), [&sum] (int n) {sum += n;});
cout << "Sum (functional C++11 lambda & for_each): " << sum << "\n";

Resources

Blogs

See also

  • C++11 - for more information on lambda expressions in C++11

Share

follow