lua-users home
lua-l archive

Re: Map and filter without intermediate tables

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


On 6/7/12, joao lobato <btnfdp.lobato@gmail.com> wrote:
> On 6/7/12, Geoff Leyland <geoff_leyland@fastmail.fm> wrote:
>> Hi,
> [...]
> local function map(f,g,t,i)
> local l = g(t,i)
> return function()
> if l == nil then return nil end
> local c = l
> l = g(t,l)
> return f(c)
> end
> end
>
> local function filter(p,g,t,i)
> local l = g(t,i)
> return function()
> if l == nil then return nil end
> local c
> repeat
> c,l = l,g(t,l)
> until c == nil or p(c) == true
> return c
> end
> end
>
> --
>
> local square = function(n) return n*n end
> local evenp = function(n) return n%2 == 0 end
>
> local t = {} ; for i=1,100 do t[i] = i end
>
> for k,v in map(square, ipairs(t)) do print(k,v) end
> for k,v in filter(evenp, map(square, ipairs(t) do print(k,v) end
>
Huh, I didn't even realize my functions are only using the first
return value of the generator.
Also, I'm missing a round bracket in the filter example. Sorry, it's too early.

AltStyle によって変換されたページ (->オリジナル) /