Skip to content

Instantly share code, notes, and snippets.

@kakkun61
Created July 8, 2012 17:26
Show Gist options
  • Save kakkun61/3071916 to your computer and use it in GitHub Desktop.
Save kakkun61/3071916 to your computer and use it in GitHub Desktop.
Functional Composition in C++ ver. 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) {
return new Function<Param2, Result>([this, g](double x){return apply(g.apply(x));});
}
};
int main(void) {
auto f = new Function<double, double>([](double x){return exp(x);});
auto g = new Function<double, double>([](double x){return pow(x, 2);});
auto h = new 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