I am trying to write a curry function in lua 5.2. My code looks like this:
function add(a, b)
return a + b
end
function curry(func, value)
return (function (...)
return func(value, table.unpack(arg))
end)
end
add2 = curry(add, 2)
print(add2(3))
The parameter arg however does not contain the value passed into the add2 function.
When I try and run the example from the Lua documentation it errors because arg is nil.
printResult = ""
function print (...)
for i,v in ipairs(arg) do -- arg is nil
printResult = printResult .. tostring(v) .. "\t"
end
printResult = printResult .. "\n"
end
How can I use variable length functions in 5.2 if this is not working?
As user @siffiejoe has pointed out, my function here is just doing partial application, not proper currying. Here is my implementation of a proper curry function in lua using the error fix from the accepted answer.
function curry(func, params)
return (function (...)
local args = params or {}
if #args + #{...} == debug.getinfo(func).nparams then
local args = {table.unpack(args)}
for _,v in ipairs({...}) do
table.insert(args, v)
end
return func(table.unpack(args))
else
local args = {table.unpack(args)}
for _,v in ipairs({...}) do
table.insert(args, v)
end
return curry(func, args)
end
end)
end
Feel free to suggest changes and add test cases here
Since Lua 5.1, arg in this context has been replaced by ... (except that the latter is a list instead of a table).
So, table.unpack(arg) should be just ....
See Breaking Changes. The Lua Reference manuals are very good and this section in particular is highly useful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With