1. Function to Apply Function to Elements of a List
In C++, we don't have native lists, but we can use std::vector. Here is the code for a function that applies a given function to each element of a vector:
#include <iostream>
#include <vector>
#include <functional>
template<typename T>
std::vector<T> transformVector(const std::vector<T>& vec, std::function<T(T)> func) {
std::vector<T> result;
for (auto& elt : vec) {
result.push_back(func(elt));
}
return result;
}
// Example usage
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
std::vector<int> squared_numbers = transformVector(numbers, [](int x) { return x * x; });
for (auto n : squared_numbers) {
std::cout << n << ' ';
}
return 0;
}
2. Curry-Style Addition Function
In standard C++, currying is not a built-in feature; however, we can achieve a similar result using lambda functions and function objects:
#include <iostream>
#include <functional>
std::function<std::function<std::function<int(int)>(int)>(int)> add = [](int a) {
return [=](int b) {
return [=](int c) {
return a + b + c;
};
};
};
// Example usage
int main() {
std::cout << add(1)(2)(3) << std::endl;
return 0;
}
3. Recursive Function for Tree Data Structure
Let's assume we have a binary tree, and we want to apply a function recursively to each node:
#include <iostream>
#include <functional>
template<typename T>
struct TreeNode {
T value;
TreeNode* left;
TreeNode* right;
TreeNode(T val, TreeNode* leftChild = nullptr, TreeNode* rightChild = nullptr)
: value(val), left(leftChild), right(rightChild) {}
};
template<typename T>
void forEachInTree(TreeNode<T>* root, std::function<void(T)> func) {
if (!root) return;
func(root->value);
forEachInTree(root->left, func);
forEachInTree(root->right, func);
}
// Example usage
int main() {
TreeNode<int>* root = new TreeNode<int>(1,
new TreeNode<int>(2),
new TreeNode<int>(3)
);
forEachInTree(root, [](int x) { std::cout << x << ' '; });
return 0;
}
These examples apply functional paradigms in C++, such as higher-order functions, lambdas, and function objects, to demonstrate functional programming principles. Please note that the functional paradigm is not the natural choice for C++, and some paradigms like immutability and avoiding side-effects are harder to enforce strictly in C++ as compared to purely functional languages like Haskell.