如何在C++中编写一对函数?

E.H*_*med -4 c++

fg是两个单参数的函数.f后面的组合物g被定义为功能x \mapsto f(g(x)).

说该程序compose实现了组合.例如,如果inc是一个向其参数添加1并square对其参数((compose square inc) 6) 求平方的过程,则 求值为49.

解决方案很简单.它看起来非常像它的数学模拟:

(define (compose f g)
  (lambda (x) (f (g x))))
Let's test:
(define (square x) (* x x))

(define (inc x) (+ x 1))

((compose square inc) 6)
Output:
 49
Run Code Online (Sandbox Code Playgroud)

如何使用C++实现组合?有可能写出这样的参数并让函数实现自己吗?

jag*_*ire 5

是的,语法非常相似:

auto compose = [](auto f, auto g){
    return [f,g](auto x){return f(g(x));};
};

auto square = [](auto i){return i * i;};

auto inc = [](auto i){return i + 1;};

compose(square, inc)(6); // result is 49
Run Code Online (Sandbox Code Playgroud)

住在coliru

[](auto arg){}是一个通用的lambda,您可以在lambda上的cppreference页面上阅读更多关于它们(和非泛型lambdas)的内容.与具有指定参数type([](int arg){})的lambda不同,它们就像带有模板化的仿函数operator(),因此允许在其使用的位置推导出它们的参数类型.