Created
July 20, 2012 01:52
-
-
Save kakkun61/3148173 to your computer and use it in GitHub Desktop.
Functional Composition in C++ ver. 2.1
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 Function<Param2, Result>([this, 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