Created
April 28, 2011 22:24
-
-
Save victusfate/947474 to your computer and use it in GitHub Desktop.
example of currying in c++
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 <stdarg.h> | |
| #include <stdlib.h> | |
| #include <iostream> | |
| using namespace std; | |
| typedef void* vp; | |
| typedef vp(*Me)(vp); | |
| template<class T> | |
| vp addOne(vp vtemp) { | |
| T *temp = (T*)vtemp; | |
| T val = 1; | |
| cout << "temp " << *temp << " val " << val << endl; | |
| *temp += val; | |
| return (vp)temp; | |
| }; | |
| template<class T> | |
| vp multByTwo(vp vtemp) { | |
| T *temp = (T*)vtemp; | |
| T val = 2; | |
| cout << "temp " << *temp << " val " << val << endl; | |
| *temp *= val; | |
| return (vp)temp; | |
| }; | |
| template<class T> | |
| vp subSeven(vp vtemp) { | |
| T *temp = (T*)vtemp; | |
| T val = 7; | |
| cout << "temp " << *temp << " val " << val << endl; | |
| *temp -= val; | |
| return (vp)temp; | |
| }; | |
| template<class T> | |
| vp divByTen(vp vtemp) { | |
| T *temp = (T*)vtemp; | |
| T val = 10; | |
| cout << "temp " << *temp << " val " << val << endl; | |
| *temp /= val; | |
| return (vp)temp; | |
| }; | |
| template <class T> | |
| vp curry(long nleft,va_list a) { | |
| if (nleft > 1) { | |
| Me f = va_arg( a, Me ); | |
| return f(curry<T>(nleft-1,a)); | |
| } | |
| else { | |
| vp varg; | |
| varg = va_arg(a,vp); | |
| T *arg = (T*)varg; | |
| cout << "extracting val from curry " << *arg << endl; | |
| return (vp)arg; | |
| } | |
| }; | |
| template <class T> | |
| T sCurry(long n,...) { | |
| va_list a; | |
| va_start(a,n); | |
| return *(T*)(curry<T>(n,a)); | |
| }; | |
| int main(int argc, char *argv[]) | |
| { | |
| if (argc != 2) { | |
| cout << argv[0] << " baseval\n"; | |
| exit(-1); | |
| } | |
| //Me is of type void* (*f)(void*), setting template function pointers | |
| Me f1 = &addOne<double>; | |
| Me f2 = &multByTwo<double>; | |
| Me f7 = &subSeven<double>; | |
| Me f10 = &divByTen<double>; | |
| double val = atof(argv[1]), val2 = atof(argv[1]); | |
| cout << "Address to base numeric " << &val << " base val " << val << endl; | |
| cout << "addOne-> " << *(double *)f1((vp)&val) << " curried addOne " << sCurry<double>(2,f1,(vp)&val2) << endl; | |
| cout << "start curry val " << val << endl; | |
| cout << "curried output f10(f7(f2(f1(val)))) or ((val+1)*2-7)/10 = " << sCurry<double>(5,f10,f7,f2,f1,(vp)&val) << endl; | |
| return 1; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment