lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


More fun:

    local function foreach_helper(fn, k, ...)
            if k ~= nil then
                fn(k, ...)
            end
            return k
    end

    local function foreach_done()
        assert(false,"seq has already been processed")
    end

    function foreach(seq, f, fn)
        local iter, state, key = seq(iterate)
        repeat
            key = foreach_helper(fn,iter(state,key))
        until key == nil
        return foreach_done
    end

    seq(ipairs(list)) (map, square) (filter, is_odd) (foreach, print)

There is probably a point where it would be faster to avoid passing the
extra fn parameter to foreach_helper on each call and instead construct
a closure, but I haven't benchmarked the crossover point and it would
probably be highly dependent on the cost of memory allocation.

This does point out the contortions one has to go through to deal with
arbitrary numbers of values.

Wiring in accumulators as final stages is going to take further
modifications to the seq object/function and protocol.

Mark