2

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?

Edit:

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

Community
  • 1
  • 1
Kelson Ball
  • 948
  • 1
  • 13
  • 30
  • 1
    Note that this is not currying, it's partial application. See e.g. [here](https://github.com/siffiejoe/lua-fx) for currying in Lua (implemented in C though). – siffiejoe Aug 03 '16 at 20:03
  • Thank you for the clarification @siffiejoe, I've added an actual curry function to the original post. – Kelson Ball Aug 03 '16 at 22:07
  • I've added a link to a github repo with the function and some test cases. Feel free to send a pull request if you have additional test cases that fail it or if you have a more ellegant solution. https://github.com/KelsonBall/LuaCurry – Kelson Ball Aug 04 '16 at 14:44

1 Answers1

11

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.

Tom Blodget
  • 20,260
  • 3
  • 39
  • 72