Skip to content

Instantly share code, notes, and snippets.

@kakkun61
Created July 20, 2012 02:47
Show Gist options
  • Save kakkun61/3148354 to your computer and use it in GitHub Desktop.
Save kakkun61/3148354 to your computer and use it in GitHub Desktop.
Functional Composition in C++ ver. 2.2
#include<iostream>
#include<functional>
#include<cmath>
using namespace std;
using namespace std::tr1;
template<typename Param, typename Result>
class Function {
public:
function<Result(Param)> apply;
Function(const function<Result(Param)> apply): apply(apply) {}
template<typename Param2>
Function<Param2, Result> compose(const Function<Param2, Param>& g) {
function<Result(Param)> apply = this->apply;
return Function<Param2, Result>([apply, g](double x){return apply(g.apply(x));});
}
};
int main(void) {
auto f = Function<double, double>([](double x){return exp(x);});
auto g = Function<double, double>([](double x){return pow(x, 2);});
auto h = Function<double, double>([](double x){return -x + 1;});
auto composed = f.compose(g).compose(h);
cout << composed.apply(3) << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment