lua-users home
lua-l archive

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


On Wed, Dec 19, 2012 at 2:35 AM, <lua-l-request@lists.lua.org> wrote:
> And everything because you want to write:
>
>     map( filter( t, is_odd ), function( _, v ) print( v ) end )
>
> instead of:
>
>     for i,v in ipairs( t ) do
>       if is_odd( i ) then
>         print( v )
>       end
>     end

It's maybe a little silly to use a map for side effects - for that you'd probably want to use a loop. Assuming you want to actually transform the values in some way, say to square them, your example might look like this:

local new_table = {}
for i, v in ipairs(t) do
    if is_odd(i) then
        table.insert(new_table, v * v)
    end
end

Which I would write like this:

    local odd_items = ifilter(is_odd, ipairs(t))
    local new_table = imap(function(i, v) return v * v end, ipairs(odd_items))

Note that all functions are flexible in that:

* You can choose whether you iterate using pairs or ipairs (or a custom iterator)
* You can choose to return either a key-value table or an array (by choosing map or imap)

/ Tom