Wednesday, July 8, 2009

map in Lua

Been looking at the Functional Library for Lua this week.

The map() implementation only works for single-argument functions. Here's a version for multiple arguments:


function map(func, ...)
local newtbl = {}
local tables = {...}
local listpos = 1
local have_args = true

while have_args do
local arg_list = {}
for i = 1, #tables do
local a = nil
a = tables[i][listpos]
if a then
arg_list[i] = a
else
have_args = false
break
end
end
if have_args then
newtbl[listpos] = func(unpack(arg_list))
end

listpos = listpos + 1
end
return newtbl
end


It is a bit more complicated, but not too bad. If anyone has suggestions on how to make it shorter and more concise, I'd appreciate it. I'm glad to be able to implement it fairly easily, in some languages it can be quite a bother.

I need to work out new version for the other functions like filter(), and post an updated version on the Lua users' wiki. foldl() might be a little interesting...

No comments: