lua-users home
lua-l archive

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


The following modification results in more efficient iteration (by stripping out the test) at the expense of having to add an explicit terminator to the sequence. I believe I've preserved the full seq semantics.

function iterate(seq)
    return seq -- not really meant to be called, but we'll make it safe
end

function seq(f, state, key)
   local function self(s, k, ...)
       if type(s) == "function" then
           if s == iterate then
              return f, state, key
           end
           f = s(self, f, k, ...) or f
           return self, state, key
       else
           return f(s, k)
       end
   end
   return self, state, key
end

-- Other material elided...

for i, x in seq(ipairs(list)) (map, square) (filter, is_odd) (iterate) do
   print(i, x)
end