Created
July 25, 2015 20:36
-
-
Save pendingchaos/2c0cf59fdb29a371f871 to your computer and use it in GitHub Desktop.
Partial partial function application.
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 <cstdio> | |
template <typename R, typename A1, typename... Args> | |
class _partialpartial | |
{ | |
public: | |
typedef R R_type; | |
_partialpartial(R (*func_)(A1, Args...), | |
A1 arg1_) : func(func_), arg1(arg1_) {} | |
inline R operator () (Args... args) const | |
{ | |
return func(arg1, args...); | |
} | |
private: | |
R (*func)(A1, Args...); | |
A1 arg1; | |
}; | |
template <typename Partial, typename A1> | |
class _partialpartial2 | |
{ | |
public: | |
typedef typename Partial::R_type R_type; | |
_partialpartial2(const Partial& partial, | |
A1 arg1_) : func(partial), | |
arg1(arg1_) {} | |
template <typename... Args> | |
inline R_type operator () (Args... args) const | |
{ | |
return func(arg1, args...); | |
} | |
private: | |
Partial func; | |
A1 arg1; | |
}; | |
template <typename R, typename A1, typename... Args> | |
inline _partialpartial<R, A1, Args...> partialpartial(R (*func)(A1, Args...), const A1& arg1) | |
{ | |
return _partialpartial<R, A1, Args...>(func, arg1); | |
} | |
template <typename Partial, typename A1> | |
inline _partialpartial2<Partial, A1> partialpartial(const Partial& partial_, const A1& arg1) | |
{ | |
return _partialpartial2<Partial, A1>(partial_, arg1); | |
} | |
int add3(int a, int b, int c) | |
{ | |
return a + b + c; | |
} | |
int main(int argc, char *argv[]) | |
{ | |
auto add = partialpartial(add3, 0); | |
auto inc = partialpartial(add, 1); | |
std::printf("5 + 1 = %d\n", inc(5)); | |
auto six = partialpartial(inc, 5); | |
std::printf("6 = %d\n", six()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment