lua-users home
lua-l archive

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


On Wed, May 13, 2009 at 3:19 AM, steve donovan wrote:
> Flemming pointed out
> that 'remove' conflicts with what we expect from table.remove, that
> is, by index. The name  'remove_at' still suggests that it is
> expecting an index.  So the search continues!

More generally, we may want to remove the first item or all items that
match a predicate.  List:filter supports that via
List:filter(curry(ne,v)), especially if it is made to operate in-place
like other List operations.  To limit it to a single remove, the
predicate may have a side-effect so as to only return true once.
Alternately, the predicate could be passed an additional index
argument that it could filter on (e.g. remove all odd-indexed
elements)--essentially a tablex.pairfilter (or ipairfilter) analogous
to tablex.pairmap.  Or List:filter might just take an optional
additional argument for the maximum number of removes, like
string.gsub.  Obviously, we may want a more efficient operation for
the common case (filter_equal), but it may be helpful to think of
remove as a specialization of filter.

On Wed, May 13, 2009 at 9:28 AM, steve donovan wrote:
> In fact, List.find_if  (or whatever it should be called) is a useful
> addition, since there are no existence-with-predicate methods for List
> except the relatively expensive List.filter followed by a non-empty
> check.

find is not just about checking existence but returning an index (or
nil if not exists).  The generalization is perhaps List.pairfilter
rather than just List.filter.

> ..., there is List.delete, which should be just
> List.remove, just like the table function, except of course it returns
> self for chaining.

That breaks a bit from table.remove, which returns the element removed
(semantically somewhat like pop).  filter and remove might be dual
things in that remove returns the element discarded, while filter
returns the elements kept.

> List.index is precisely the same as tablex.find (the latter's name
> seems to come from the STL, hence find_if). Having  two names for
> exactly the same operation is less than optimal.  ('find' has
> precedent in string.find.)

There's a number of similarities with string (conceptually a list of
characters) -- string.sub (as you mentioned, like slice),
string.reverse, string.rep (currently absent in List/tablex), and
string.len.

The string.match, string.find, string.gsub, and string.gmatch are more
general in that they match a sub-list (rather than single element)
against a list.  By strict analogy, we would have
tablex.find({5,6,7,8,9}, {7,8}) == 3, but this sub-list matching is
probably rarely useful except for strings; hence,
tablex.find({5,6,7,8,9}, 7) == 3 instead.

> About List.reverse - it does _internally_ create a temporary, but then
> copies it back.

Swapping the list elements in-place would make more sense there.