Because Lua only provides a small set of utility functions, the functional primitives which I'm used to having for working on lists with are not there. However, since Lua provides higher-order functions, adding them was easy. My lambda.lua file provides implementations of map, filter and reduce.
The official documentation:
A list of the accumulated results of calling fn() on every element of the given lists.
To double all of the elements in a list:
> lambda.map(function(a) return a * 2 end, {1, 2, 3})
-> {2, 4, 6}
Or to find the sum of each of the corresponding elements in the two lists:
> lambda.map(function(a, b) return a + b end, {1, 2, 3}, {4, 5, 6})
-> {5, 7, 9}
function map(fn, ...)
assert(arg.n > 0, "map() must be called with at least one list.")
local lists = {}
for i = 1, arg.n do table.insert(lists, arg[i]) end
-- go through each of the elements in lists and call fn() on each
-- set of elements
res = {}
for i, _ in pairs(lists[1]) do
-- collect one argument from each of the lists
local this_arg = {}
for _, l in pairs(lists) do table.insert(this_arg, l[i]) end
-- collect the results of applying fn() to it
table.insert(res, fn(unpack(this_arg)))
end
return res
end
Pick elements out of a list which match a given criteria.
A list of elements in list which satisfy by the given function.
> lambda.filter(function(a) return (a % 2 == 0) end, {1, 2, 3, 4, 5, 6})
-> {2, 4, 6}
function filter(fn, list)
local ret = {}
for _, elem in pairs(list) do
if fn(elem) then table.insert(ret, elem) end
end
return ret
end
Apply a calculation successively down the elements of a list to accumulate a single value.
A single value which is the accumulation of calling fn(a, b) on each pair of successive elements in the list.
> lambda.reduce(function(a, b) return a + b end, 0, {1, 2, 3, 4})
-> 10
function reduce(fn, initial, list)
local ret = initial
for _, elem in pairs(list) do
ret = fn(ret, elem)
end
return ret
end
Download: lambda-lua.tar.gz