Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save egtra/2007773 to your computer and use it in GitHub Desktop.
Save egtra/2007773 to your computer and use it in GitHub Desktop.
C++11のラムダ式で再帰
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
typedef std::function<int (int)> F;
F Fix(std::function<F (F)> f)
{
return [=](int t) {return f(Fix(f))(t);};
}
using namespace std;
int main(){
vector<int> v = {1, 2, 3, 4, 5};
// vの要素をそれぞれ階乗して出力
for_each(v.begin(), v.end(), [](int const i){ // 出力用の無名関数
cout <<
Fix([](F f) -> F{ // 「階乗する無名関数」を返す関数。
return [=](int n){
return ((0 == n)?(
1
):(
n * f(n - 1)
));
};
})(i) <<
endl;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment