fork(4) download
  1. #include <functional>
  2.  
  3. namespace _dtl {
  4.  
  5. template <typename FUNCTION> struct
  6. _curry;
  7.  
  8. // specialization for functions with a single argument
  9. template <typename R,typename T> struct
  10. _curry<std::function<R(T)>> {
  11. using
  12. type = std::function<R(T)>;
  13.  
  14. const type
  15. result;
  16.  
  17. _curry(type fun) : result(fun) {}
  18.  
  19. };
  20.  
  21. // recursive specialization for functions with more arguments
  22. template <typename R,typename T,typename...Ts> struct
  23. _curry<std::function<R(T,Ts...)>> {
  24. using
  25. remaining_type = typename _curry<std::function<R(Ts...)> >::type;
  26.  
  27. using
  28. type = std::function<remaining_type(T)>;
  29.  
  30. const type
  31. result;
  32.  
  33. _curry(std::function<R(T,Ts...)> fun)
  34. : result (
  35. [=](const T& t) {
  36. return _curry<std::function<R(Ts...)>>(
  37. [=](const Ts&...ts){
  38. return fun(t, ts...);
  39. }
  40. ).result;
  41. }
  42. ) {}
  43. };
  44. }
  45.  
  46. template <typename R,typename...Ts> auto
  47. curry(const std::function<R(Ts...)> fun)
  48. -> typename _dtl::_curry<std::function<R(Ts...)>>::type
  49. {
  50. return _dtl::_curry<std::function<R(Ts...)>>(fun).result;
  51. }
  52.  
  53. template <typename R,typename...Ts> auto
  54. curry(R(* const fun)(Ts...))
  55. -> typename _dtl::_curry<std::function<R(Ts...)>>::type
  56. {
  57. return _dtl::_curry<std::function<R(Ts...)>>(fun).result;
  58. }
  59.  
  60. #include <iostream>
  61.  
  62. void
  63. f(std::string a,std::string b,std::string c)
  64. {
  65. std::cout << a << b << c;
  66. }
  67.  
  68. int
  69. main() {
  70. curry(f)("Hello ")("functional ")("world!");
  71. return 0;
  72. }
Success #stdin #stdout 0s 3280KB
stdin
Standard input is empty
stdout
Hello functional world!