lua-users home
lua-l archive

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


On Fri, Dec 25, 2009 at 1:28 PM, spir <denis.spir@free.fr> wrote:
> This is an attempt at solving the here often debated issue of short anonymous funcs such as
>    x --> x * x
>    function(x) return x * x end
> in a simplistic manner, in the case where a single variable is in play. This is rather intended to be used in higher-order funcs such as map or filter.

I liked this way of doing things, but David M has pointed out that
making the function argument of map, etc to be a special string is a
problem for two reasons:
(1) A person may make their strings directly callable, by setting
getmetatable("").__call.
(2) It is implicit behaviour and makes these functions harder to
describe precisely.

So by the 'be explicit in Lua' principle, you would call formula directly:

t = map(t,formula "_*_")

(BTW, what precisely is the default character given? It appears to be 0xA4?)

We can go a little further, and allow for strings like '_1*_2' meaning
function(x,y) return x*y end.

As for the order of map() arguments. I originally defined them as
(table,function) in the first iteration of Penlight (it felt natural
to put the function last), but was persuaded that the 'canonical'
order is (function,table). Maybe we should reconsider this, since all
of the table functions have the table as first argument, i.e. as the
'self' parameter.  Consider this entertaining little trick:

local TMT = {__index = table}

function table.new(t) return setmetatable(t,TMT) end

local T = table.new  -- alias
t = T{'one','two'}
print(t:concat())
=>
one,two

(There have been questions about why this isn't the default state of
newly created tables, but it's better to make this explicit)

Now, if map, filter etc consistently have the table as the self
argument, then things work as expected, e.g. t:map(string.upper).

However, this argument order means that map() takes precisely one
table argument, so you can't do the generalization-to-n-tables (map2
etc) which Fabien has in his version of table.imap in the Metalua
libraries.

steve d