Skip to content

Instantly share code, notes, and snippets.

@domgetter

domgetter/currying.cpp

Last active Jan 23, 2016
Embed
What would you like to do?
// 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