| lambda-expressions/lambda4.cc - A function that returns a function - OK. | Lecture 3 - slide 2 : 27 Program 7 |
// A function that returns the value of a lambda expression - a closure.
// The closure refers a global variable, seed, instead of a dangling local variable in f.
// This compiles and runs. But it is rather primitive seen from a functional programming point of view.
#include <iostream>
#include <string>
#include <functional> // std::function
int seed;
std::function<int(int)> f(const int seed0){
seed = seed0; // Assigning global variable
return [](int i){
seed++;
return i + seed;
};
}
int main () {
using namespace std;
auto g = f(5); // f(5) returns a function that can access the
// global seed. OK. But not that interesting.
for(int i = 1; i <= 5; i++)
cout << "g(" << i << ") = " << g(i) << endl; // 7, 9, 11, 13, 15
}