Created
November 27, 2014 02:52
-
-
Save anonymous/5147371480d164dffb4a to your computer and use it in GitHub Desktop.
map/reduce function for lua
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- | |
-- convenience functional utilities | |
-- | |
-- map(table, function) | |
-- e.g: map({1,2,3}, function(a) return a*2 end) -> {2,4,6} | |
function map(tbl, func) | |
local newtbl = {} | |
for i,v in pairs(tbl) do | |
newtbl[i] = func(v) | |
end | |
return newtbl | |
end | |
-- filter(table, function) | |
-- e.g: filter({1,2,3,4}, function(a) return a%2==0 end) -> {2,4} | |
function filter(tbl, func) | |
local newtbl = {} | |
for i,v in pairs(tbl) do | |
if func(v) then | |
newtbl[i] = v | |
end | |
end | |
return newtbl | |
end | |
-- head(table) | |
-- e.g: head({1,2,3}) -> 1 | |
local function head(tbl) | |
return tbl[1] | |
end | |
-- tail(table) | |
-- e.g: tail({1,2,3}) -> {2,3} | |
local function tail(tbl) | |
local size = #tbl | |
if size > 0 then | |
return {unpack(tbl, 2)} | |
end | |
end | |
-- foldr(table, default_value, function) | |
-- e.g: foldr({1,2,3,4,5}, 1, function(a, b) return a*b end) -> 120 | |
local function foldr(tbl, val, func) | |
for i, v in pairs(tbl) do | |
val = func(val, v) | |
end | |
return val | |
end | |
-- reduce(table, function) | |
-- e.g: reduce({1,2,3,4}, function(a, b) return a+b end) -> 10 | |
function reduce(tbl, func) | |
return foldr(tail(tbl), head(tbl), func) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment