lua-users home
lua-l archive

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



> It's maybe a little silly to use a map for side effects - for that you'd
> probably want to use a loop.

Why? Because map unfortunately constructs a superfluous table?

Yes, because the conventional use of a map is to transform something. This convention dates at least as far back as Lisp, which in turn would have borrowed it from mathematics (hence the name "map").
 
Let's
call the function 'each' like in underscore.js or its Lua equivalent[1]
or Ruby (or table.foreachi like in previous Lua versions).

I don't tend to use functions like 'each' or 'foreach', for that use case I would just use an idiomatic Lua loop.


>
> 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))

Ok, you have the iterators variant of map/filter, at least for the
input, but not the output. If I were to use map/filter, I would choose
my version[2] with iterator input and output.
 
The example would look like

     local new_t = {}
     for _,w in map( function( i, v ) return v * v end, filter( is_odd,
ipairs( t ) ) ) do
       new_t[ #new_t+1 ] = w
     end

Returning iterators works ok, but is a) harder to chain (try adding a couple more transformations and you'll see what I mean) and b) can get a little awkward when you want to store the final result.

As it stands your example still contains the boilerplate of creating and assigning to a new table.

> So you are *nearly* as flexible (no
> break, only one key + one value, no numeric for, can't handle arrays
> with holes, etc.) and *nearly* as efficient as Lua's for loop with 4
> additional public functions (2 in my case). 

map, filter, reduce, fold etc. don't intend to be flexible, they intend to capture common computational patterns. For the case that I can't express something using a combination of functional primitives, I would fall back to using plain imperative loops.

In terms of efficiency I wouldn't worry too much about creating a few extra tables. If you're looking at a performance hotspot you can write imperative code or fall back to C as needed.

/ Tom