lua-users home
lua-l archive

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


Curiosity led me to rewrite your version without using temporary tables:

local function step(state, filter, iter, ...)
  local h = select(1,...)
  if h == nil then return nil end
  if filter(...) then return ... end
  return step(state, filter, iter, iter(state, h))
end

function iterfilter2(filter, iter, state1, var1)
  return function(state2, var2)
    return step(state2, filter, iter, iter(state2, var2))
  end,
  state1, var1
end

I doubt it's a good idea :-)

On 22/12/2012, Kevin Martin <kev82@khn.org.uk> wrote:
>
> On 22 Dec 2012, at 16:19, joao lobato wrote:
>
>> However, all that packing and unpacking is bound to have a performance
>> hit.
>
> I hadn't considered that, as in almost all cases there is only one return
> value. I will think about your suggestions, thanks.
>
> On 22 Dec 2012, at 16:34, Dirk Laurie wrote:
>
>> Is there a reason why the obvious Lua code is inefficient, obscure
>> or not applicable?
>
> I want to write the following code:
>
> for a in carer:availBlocks() do
> 	--do something with a
> end
>
> I do not want to write:
>
> for a in carer:toProblem():availBlocks() do if carer:id() == a:carer():id()
> then
> 	--do something with a
> end
>
> Without an iterator filter, the only way I can think to implement,
> carer.availBlocks is to use a temporary table:
>
> function carer_mt.availBlocks()
> 	local t = {}
> 	for b in self:toProblem():availBlocks() do
> 		if b:carer():id() == self:id() then
> 			t[b] = true
> 		end
> 	end
> 	return pairs(t)
> end
>
> Sometimes there are 1000s of elements and repeatedly creating the temporary
> table for every time I iterate seems like a bad idea.
>
> Thanks,
> Kevin
>