Just whipped up this quick curry function in Lua, as a building block for partial application and memoization. Any feedback is appreciated.
It takes two arguments; n
is the number of parameters in the function being curried, and func
is the function to curry.
Code generation is used to create the curried functions. Because the same code is generated for any given n
, the generated functions are cached to offset the runtime cost of code generation.
local curryCache = {}
local function curryGenerate(n)
if curryCache[n] then return curryCache[n] end
local src = 'return func(a1%s)'
for i = 2, n do
src = src:format((', a%i%%s'):format(i))
end
src = src:format('')
for i = n, 1, -1 do
src = ('return function(a%i) %s end'):format(i, src)
end
src = ('local func = ...; %s'):format(src)
curryCache[n] = load(src)
return curryCache[n]
end
local function curry(n, func)
return n < 2 and func or curryGenerate(n)(func)
end
Testing it out:
local p4 = curry(4, print)
p4 'a' 'b' 'c' 'd' -- prints "a b c d"
Looking at some other questions about currying on this site, I noticed some use a more loose definition of the term, where any number of arguments can be passed to the curried function. I'm shooting for a more strict interpretation here, where the curried function, and each function returned by it, only takes a single argument.
I'm also more concerned with the performance of the curried functions than the performance of curry
, so code generation seems like a logical approach. But of course the performance of curry
is also something worth considering for some use cases, so I'm open to alternate suggestions that do away with code generation, as long as the performance of the curried functions isn't impacted too drastically.