lua-users home
lua-l archive

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


Am 19.12.2012 17:40, schrieb Philipp Janda:

[...]

local f1, s1, v1 = ipairs( t )
local f2, s2, v2 = filter( is_odd, f1, s1, v1 )
local f3, s3, v3 = map( function( i, v ) return v * v end, f2, s2, v2 )
local new_t = icollect( 2, f3, s3, v3 )   -- [1]

[... 4 public functions, bla bla ...]


Thinking about it: one could merge filter and map into one function. If the provided function returns a nil value, skip/remove that whole (i)pair/tuple altogether, else the return value is the new value. Let's call this function "transmogrify" (I always wanted to call a function transmogrify and I think nobody has any particular expectations for such a function). One down! And collect/icollect ([1], slightly altered) are actually surprisingly interesting:

    icollect( {}, 1, pairs( t ) )        --> keys( t )
    icollect( {}, 2, pairs( t ) )        --> values( t )
    icollect( {}, 2, ipairs( t ) )       --> shallow_arraycopy( t )
    icollect( {}, 1, io.lines( fname ) ) --> my @lines = <FILE>;
    icollect( t1, 2, ipairs( t2 ) )      --> append( t1, t2 )

    collect( {}, 1, 2, pairs( t ) )  --> shallow_tablecopy( t )
    collect( {}, 1, 2, ipairs( t ) ) --> shallow_arraycopy( t )
    collect( {}, 2, 1, ipairs( t ) ) --> invert( t ), makeset( t )
    collect( t1, 1, 2, pairs( t2 ) ) --> extend( t1, t2 )

Four more down! :-)

Philipp




   [1]:
     do
       local function icollect_helper( t, i, n, f, s, var_1, ... )
         if var_1 ~= nil then
           t[ i ] = select( n, var_1, ... )
           return icollect_helper( t, i+1, n, f, s, f( s, var_1 ) )
         end
         return t, i-1
       end

       function icollect( t, n, f, s, var )
         return icollect_helper( t, #t+1, n, f, s, f( s, var ) )
       end
     end