I was learning about code currying, and search for a example in lua, and find this: reddit link (last comment)
function add(a,b)
return a+b
end
function curry(fn, args, arg, first)
args = args or {}
args[#args+1] = arg
return (arg or not first) and function(arg)return curry(fn,args,arg,1)end or fn(table.unpack(args))
end
local sumone = curry(add)(1)
print(sumone(3)()) --> 4
print(curry(add)(2)(3)()) --> 5
Can someone explain a bit? fn is function, args is arguments, arg is argument and first is what? And what is that return? Any help is welcome
Edit: I find that they make a whole function on the return
return
(arg or not first) and
function(arg)
return curry(fn,args,arg,1)
end
or
fn(table.unpack(args))
fn: This is the original function that you want to curry. In your example, add is the function that takes two arguments and returns their sum.
args: This is a table that stores the arguments as they are being collected during the currying process. It is initialized as an empty table ({})
arg: This is the current argument being passed to the curried function. It gets added to the args table.
first: This is a flag indicating whether this is the first argument being passed. If it’s true, it means this is the initial call and not a recursive one. If it’s false or nil, it means that the function is being called recursively with additional arguments.
return (arg or not first) and function(arg) return curry(fn, args, arg, 1) end or fn(table.unpack(args))
(arg or not first): This part checks if arg is provided (not nil) or if it’s not the first argument. If true, it means there are more arguments to collect or the currying process is ongoing.
function(arg) return curry(fn, args, arg, 1) end: If there are more arguments to collect, it returns a new function that continues the currying process. This new function will take the next argument and call curry recursively.
or fn(table.unpack(args)): If there are no more arguments to collect (either because all arguments are collected or it’s the initial call), it invokes the original function fn with the collected arguments using table.unpack(args).
return statement handles the logic of whether to return a new function for further currying or to invoke the original function with the collected arguments. If there are more arguments to collect (arg is provided or it’s not the first argument), it returns a new function; otherwise, it invokes the original function.