Advertisement
Guest User

Untitled

a guest
May 5th, 2015
233
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.34 KB | None | 0 0
  1. import std.traits;
  2. import std.typecons;
  3.  
  4. private struct Curry(alias Func, size_t Index = 0) {
  5. private alias _Types = ParameterTypeTuple!Func;
  6. private Tuple!(_Types[0 .. Index]) _args;
  7.  
  8. static if (Index + 1 == _Types.length) {
  9. ReturnType!Func opCall(_Types[Index] arg) {
  10. return Func(_args.expand, arg);
  11. }
  12. } else {
  13. auto opCall(_Types[Index] arg) {
  14. Curry!(Func, Index + 1) curry;
  15. curry._args = tuple(_args.expand, arg);
  16. return curry;
  17. }
  18. }
  19. }
  20.  
  21. auto curry(alias Func)() {
  22. Curry!(Func, 0) curry;
  23. return curry;
  24. }
  25. auto curry(alias Func, T)(T arg) {
  26. return curry!Func()(arg);
  27. }
  28.  
  29. unittest {
  30. import std.stdio;
  31.  
  32. int f(int x, int y, int z) {
  33. return x * y * z;
  34. }
  35.  
  36. writeln(curry!f);
  37. writeln(curry!f(2));
  38. writeln(curry!f(2)(3));
  39. writeln(curry!f(2)(3)(4));
  40. assert(f(2, 3, 4) == curry!f(2)(3)(4));
  41.  
  42. auto a = curry!f;
  43. assert(f(2, 3, 4) == a(2)(3)(4));
  44. auto b = a(3);
  45. assert(f(3, 4, 5) == b(4)(5));
  46. auto c = a(4);
  47. assert(f(4, 5, 6) == c(5)(6));
  48.  
  49. enum A = curry!f;
  50. static assert(f(1, 2, 3) == A(1)(2)(3));
  51. enum B = curry!f(1);
  52. static assert(f(1, 2, 3) == B(2)(3));
  53. enum C = curry!f(1)(2);
  54. static assert(f(1, 2, 3) == C(3));
  55. enum D = curry!f(1)(2)(3);
  56. static assert(f(1, 2, 3) == D);
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement