Skip to content

Instantly share code, notes, and snippets.

Created November 27, 2014 02:52
Show Gist options
  • Select an option

  • Save anonymous/5147371480d164dffb4a to your computer and use it in GitHub Desktop.

Select an option

Save anonymous/5147371480d164dffb4a to your computer and use it in GitHub Desktop.

Revisions

  1. @invalid-email-address Anonymous created this gist Nov 27, 2014.
    55 changes: 55 additions & 0 deletions functional.lua
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,55 @@
    --
    -- 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