Skip to content

Instantly share code, notes, and snippets.

@domgetter
Last active January 23, 2016 02:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save domgetter/bd4c21821267b63faea0 to your computer and use it in GitHub Desktop.
Save domgetter/bd4c21821267b63faea0 to your computer and use it in GitHub Desktop.
// Run online: https://eval.in/506636
#include <iostream>
#include <functional>
// curries any function from (int, int) -> int into int -> (int -> int)
auto curry(int (*func)(int, int)) -> std::function<std::function<int (int)> (int)> {
return [func] (int x) {
return [func, x] (int y) {
return func(x, y);
};
};
}
int main (int argc, char ** argv) {
auto add = [] (int x, int y) -> int { return x + y; };
auto mult = [] (int x, int y) -> int { return x * y; };
auto inc = curry(add)(1);
auto doub = curry(mult)(2);
std::cout << " 2 incremented is: " << inc(2) << std::endl;
std::cout << " 8 doubled is: " << doub(8) << std::endl;
std::cout << "the sum of 2 and 3 is: " << add(2, 3) << std::endl;
std::cout << "the sum of 2 and 3 is: " << curry(add)(2)(3) << std::endl;
return 0;
}
/* Output:
2 incremented is: 3
8 doubled is: 16
the sum of 2 and 3 is: 5
the sum of 2 and 3 is: 5
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment