Lua map/filter/reduce

Date: 2020-11-17

https://devforum.roblox.com/t/functional-shenanigans-map-filter-partition-reduce-two-ways/199027

function map(sequence, transformation)
    local newlist = {}
    for i, v in pairs(sequence) do
        newlist[i] = transformation(v)
    end
    return newlist
end

function filter(sequence, predicate)
    local newlist = { }
    for k, v in pairs(sequence) do
        if predicate(v) then
            table.insert(newlist, v)
        end
    end
end

function ifilter(sequence, predicate)
    local newlist = { }
    for i, v in ipairs(sequence) do
        if predicate(v) then
            table.insert(newlist, v)
        end
    end
end

function filter2(sequence, predicate)
    local newlist = { }
    for k, v in pairs(sequence) do
        if predicate(v) then
            newlist[k] = v
        end
    end
end

function reduce(sequence, operator)
    if #sequence == 0 then
        return nil
    end
    local out = nil
    for i=1,#sequence do
        out = operator(out, sequence[i])
    end
    return out
end

function partition(sequence, predicate)
    local left = {}
    local right = {}
    for i, v in ipairs(sequence) do
        if (predicate(v)) then
            table.insert(left, v)
        else
            table.insert(right,v)
        end
    end
    return left, right
end
42850cookie-checkLua map/filter/reduce