github.com/coyove/nj@v0.0.0-20221110084952-c7f8db1065c3/tests/curry.nj.lua (about) 1 function curry(f, args...) 2 assert.shape(f, "@function") 3 local ac = f.argcount() 4 if f.isvarg() then ac -= 1 end 5 if #args >= ac then return f.call(args...) end 6 7 local cf = function(args...) 8 self.args.concat(args) 9 if #args >= self.args_needed then 10 return self.f.call(self.args...) 11 end 12 local new_cf = self.copy(true) 13 new_cf.args_needed = self.args_needed - #args 14 return new_cf 15 end 16 cf.f = f 17 cf.args = args or [] 18 cf.args_needed = ac - #args 19 return cf 20 end 21 22 curry(print, "begin currying") 23 24 function add(a, b, c) 25 return a+b+c 26 end 27 28 assert(curry(add, 1, 2)(3), 6) 29 assert(curry(add, 1)(2)(3), 6) 30 assert(curry(add)(1)(2)(3), 6) 31 32 function sizeof(c...) 33 return #c 34 end 35 36 assert(curry(sizeof), 0) 37 assert(curry(sizeof, 1), 1) 38 39 function addv(a, b, c...) 40 local res = a + b 41 for _, ca in c do 42 res += ca 43 end 44 return res 45 end 46 47 assert(curry(addv, 1, 2), 3) 48 assert(curry(addv, 1)(2), 3) 49 assert(curry(addv)(1)(2, 3), 6) 50 51 print(curry(addv))