Skip to content

Instantly share code, notes, and snippets.

@sharpobject
Created August 26, 2013 19:47
Show Gist options
  • Save sharpobject/6345801 to your computer and use it in GitHub Desktop.
Save sharpobject/6345801 to your computer and use it in GitHub Desktop.
Curry things in lua! TODO: make this less terrible, or just don't use it, gosh.
local function dummy()end
local funcmt = getmetatable(dummy)
if not funcmt then
funcmt = {}
debug.setmetatable(dummy,funcmt)
end
funcmt.__index = funcmt.__index or {}
local type,select = type,select
assert(type(funcmt.__index) == "table")
local function curry(f, ...)
if(select("#", ...) == 0) then
return f
else
local first_arg = select(1, ...)
local function onearg(...)
return f(first_arg, ...)
end
return curry(onearg, select(2, ...))
end
end
local function rotate_left_internal(howmuch, idx, n, ...)
if n == idx then return end
return select(((idx + howmuch) % n) + 1, ...),
rotate_left_internal(howmuch, idx + 1, n, ...)
end
local function rotate_left(howmuch, ...)
local n = select("#", ...)
return rotate_left_internal(howmuch, 0, n, ...)
end
-- for some reason I thought this would help???
--[[local function reverse_internal(idx, n, ...)
if n == idx then return end
return select(n - idx, ...), reverse_internal(idx + 1, n, ...)
end
local function reverse(...)
local n = select("#", ...)
return reverse_internal(0, n, ...)
end--]]
local function rcurry(f, ...)
local n = select("#", ...)
return curry(function(...)
return f(rotate_left(n, ...))
end, ...)
end
funcmt.__index.curry = curry
funcmt.__index.rcurry = rcurry
print:rcurry(6,7,nil):curry(1,2,3)(4,5)
-- equivalent to print(1,2,3,4,5,6,7,nil)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment