Created
July 8, 2012 17:26
-
-
Save kakkun61/3071916 to your computer and use it in GitHub Desktop.
Functional Composition in C++ ver. 2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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