In functional programming (FP), there are some important features:
- First class function.
- Lambda function.
- Lexical closure.
This can be found in Lisp, Ruby ... but not C++, or Java, in the past.
Now C++ 11 has arrived, and this can be easily implemented in C++ too.
Let me show you an example:
#include <iostream>
#include <functional>
auto makeAdder = [](int n) {
return [=](int val) { return val + n; };
};
int main() {
int n = 0;
std::cin >> n;
auto addn = makeAdder(n);
std::cout << addn(4) << std::endl;
return 0;
}
Compile:
g++ -std=c++11 example1.cpp -o example1
Run:
./example
Input 1, print 5 .