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, ...)
            return k

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

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

    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.