Lazy filter

A lazy filter.
mail@pastecode.io avatar
unknown
lua
2 years ago
838 B
9
Indexable
Never
-- Lua 5.1
local function filter(iterable, predicate, default)
    local idx = 1
    return function()
        while idx < #iterable do
            local element = iterable[idx]
            if predicate(element) then 
                idx = idx + 1
                return element
            end
            idx = idx + 1
        end
        if type(default) == "function" then return default() end
        return default
    end
end


local iterable = {
    [1] = 0,
    [2] = 1,
    [4] = 2
}

local function even(x)
    if x ~= nil then return math.fmod(x, 2) == 0
    else return false
    end
end


-- To prevent weird behaviour
local function err()
    error("Iterator already at end!")
end
local filtered_generator = filter(iterable, even, err)

local iterlen = #iterable
for i = 0, iterlen do
    io.write(filtered_generator())
end