lua-users home
lua-l archive

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


On 6/7/12, Geoff Leyland <geoff_leyland@fastmail.fm> wrote:
> On 7/06/2012, at 7:45 PM, joao lobato wrote:
>
>> Your code looks very convoluted.
>
> Yes.  I'd rather it weren't.  Some of it is to get nice features though -
> what's returned by map is both an iterator and can be called by pairs.
>
>> When I want to iterate over the (i)pairs of a table without
>> intermediate tables I use these two guys:
>> [...]
>
> This is nice.  I'd avoided closures because FNEW (creating a closure)
> doesn't get compiled by LuaJIT, but there aren't actually many FNEWs in
> there.  (I avoided coroutines for a similar reason - yield and resume aren't
> compiled and there can be plenty of them) and because you can't set a
> metatable (and hence __pairs) on a function or thread.  But it is easier on
> the eyes.
>
> Unfortunately, not faster.  But I rewrote filter using a repeat, which is
> much nicer than while true do, and it got map (but not imap) considerably
> quicker for luajit.
>
> (By the way, I've updated the gist to take account of Dirk, Steve and your
> comments)
>

FWIW, my experience with maps and filters and folds is that you don't
really want them. If you have an array, use a numeric for. If you're
iterating over the contents of an hash table, you're using it wrong.

There are too many alternatives. Take filter: you may want to apply
the predicate to the keys or to the values; or maybe you want
sequencial keys in the final sequence rather than the original keys.

In general, it is best just to write the for loop and be done with it.
A 'for' with an 'if' is certainly much clearer than that 'repeat'.
Also of note is that ipairs stops at the first nil while 'for i=1,#t
do end' will take __len into consideration.

I'm rambling now :-), but it is like Reduce in Lisp: you can
accomplish pretty much everything with it but you must remember what
the signature of the fold function should be; OTH, you have the map
family, do, loop, dolist, dotimes or even just write your own
recursive function...