lua-users home
lua-l archive

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


Norman Ramsey wrote:
> local sizes = table.map(function(s) return s:gsub('%A', ''):lower() end, names)
>
>but
>
> local sizes = table.map(\s -> s:gsub('%A', ''):lower(), names)
>
>fits easily and is (in my opinion) easier to read.

In Haskell, I find that I rarely use the lambda syntax because having
a named parameter suggests that the function is complex enough that
the point-free style will not suffice.  To me, that means the function
is worthy of a name.

Encoding Norman's example in Haskell:

   sizes names = map (\s -> lower (gsub "%A" "" s)) names

First, a few reductions using Richard Bird's notation for equational reasoning:

=    {break into two functions}
   sizes names = map replace names
   replace s = lower (gsub "%A" "" s)

=    {go point-free}
   sizes = map replace
   replace = lower . gsub "%A" ""

=    {inline 'replace'}
   sizes = map (lower . gsub "%A" "")

Lua doesn't support point-free programming, so to encode in Lua, I'd
backtrack to the last reduction without the point-free style:

   sizes names = map replace names
   replace s = lower (gsub "%A" "" s)

=    {encode in Lua, assume 'names' is in scope}
   local replace = function(s) return s:gsub("%A", ""):lower() end
   local sizes = map(replace, names)

=    {add syntactic sugar}
   local function replace(s)
      return s:gsub("%A", ""):lower()
   end
   local sizes = map(replace, names)


At this point, if you are keen on inlining 'replace', I'd follow the
Ruby's convention for blocks and push the function argument to the
last parameter.  This lets you split the function over a few lines to
make it more readable as well as enabling Lua's syntactic sugar for
object-oriented programming:

=    {encode in Ruby}
   sizes = names.map do |x|
      s.gsub("%A", "").lower
   end

=    {encode in Lua}
   local sizes = names:map(function(s)
      return s:gsub("%A", ""):lower()
   end)

It is my opinion that Lua's verbose syntax for anonymous functions
makes Lua easier to learn, easier to implement, and encourages better
programming style.

Thanks,
Greg Fitzgerald