Can someone explain this code? (Currying example)

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)) 
  1. 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.

  2. 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 ({})

  3. arg: This is the current argument being passed to the curried function. It gets added to the args table.

  4. 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.

1 Like

that will explain, thank you a lot <3

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.