定义一个返回调用参数函数指定次的函数的函数

如果 f 是一个数值函数, 那么就可以通过反复调用 f,通过 f(f(f(x)))... 来实现调用 n 次 f 函数。

如果把此过程设为 Repeated, 那么

Repeated(Square, 2)(5)

的结果应该是625。

我觉得看了上一篇博客的朋友应该会觉得这很简单:

iFun Compose (iFun f, iFun g) { return [=] (cint &x) {return f(g(x));}; } iFun Repeated (iFun f, cint &times) { if (times < 2) { return f; } else { return Repeated(Compose(f, f), (times - 1)); } } int main () { ios::sync_with_stdio (false); cout << Repeated ([] (cint &i) {return static_cast<int>(pow(i, 2));} , 2)(5); cout << endl; return 0; }

 

你可能感兴趣的:(函数)