lua-users home
lua-l archive

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


Hi list,
Does anyone use short anonymous functions with Lua ports of higher-order stuff like map, grep (filter), reduce, zip and the rest of the lot? I use these things a lot in Perl and Ruby and was wondering why they aren't part of the standard library. Until recently, that is, when I ported some of those functions to lua as coroutine based iterators, and discovered the hard way they are not practical quite the same way as in the other scripting languages. This is not a complaint, just an observation.

The problem to me is the syntax. A map doing nothing looks lie:

map(function(e) return e end, list)

Quite a lot of typing and as soon as the processing gets much more complex, you might as well give the callback function a name in the first place. compared to just (Perl):

map $_, @list;

or

map { $_ } @list;

So the fact that you do need to name your parameters, do need the return keyword, the keyword for function being function rather than def or sub etc... majorly contributes to this. NOt only that but Perl has a lot of magic related to the $_ variable, making code using it quite short. map is also, in that language, great for populating hashes based on assigning subsequent list elements, mapping file names to their sizes, for example:

my %hash = map { $_, -s } <*.txt>;

Again, Lua does not have all that syntactic sugar to make this very useful. I don't think it should, either.

In Perl and Ruby (in the little I've coded the latter) the one final idiom I use is list processing statements that do many things e.g. two maps, map and a grep etc... Because the syntax is not verbose, the PErl version is brief. and because they are chained method calls, the Ruby version reads left to right, which I find to be a huge advantage when reading code with a speech synth. stuff such as (untested, slightly modded from old code of mine):

def rgb_dif firstRgb, secondRgb
(firstRgb.zip secondRgb).map do|component|
 (component[0] - component[1]).abs
end
end

This is just something I thought I'd post about seeing the recent thread on assignment statements. Speaking of Perl and Lua, even as a newbie to the language,I like Lua immensely and found it easy to pick up due to the strong perl parallelisms like heavy use of hashes and the OOP. Because of that I have a tutorial for Perlers, though be warned, the text is alpha quality:

http://vtatila.kapsi.fi/luatut.html

PS: in a way the anonymous function syntax of Lua is extremely logical. Like a function without the name, with the parameter list, return statement and all.

--
With kind regards Veli-Pekka Tätilä
Accessibility, Apps and Coding plus Synths and Music:
http://vtatila.kapsi.fi