lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Sorry, I couldn't resist. The generalised curry function
(memoise was in some other post) showing an interesting
example of on-the-fly compilation:

do
  local function currifier(n)
    local i = 0
    local a = string.gsub("a#" .. string.rep(", a#", n - 1),
                          "#",
                          function() i = i + 1; return i end)
    return loadstring ([[
      return function(fn, ]] ..a.. [[)
        return function(...)
          return fn(]] ..a.. [[, unpack(arg))
        end
      end
    ]])()
  end

  local curries = memoise(currifier)
  curries[0] = function(fn) return fn end

  function curry(fn, ...)
    return curries[arg.n](fn, unpack(arg))
  end
end