I HAVE BEEN reading up on Python programming lately (more on that in a later post). I’ve now been introduced to anonymous functions. In Python, anonymous functions are available using the lambda keyword. Anonymous functions are great, but I think the Lua syntax for anonymous functions is superior to the syntax adopted in Python.

A normal function, in Python, is defined using the def keyword along with a function name.

>>> def f1(x, y):
...     return x + y
>>> f1(1, 2)

In Python anonymous functions are created by a lambda expression.

>>> f2 = lambda x, y: x + y
>>> f2(1, 2)

Similar to anonymous function, normal Python functions are first class objects and can be assigned to other variables.

>>> f = f1
>>> f(1, 2)

However direct assignment of a function deceleration is not possible.

>>> f = def f3(x, y):
  File "", line 1
    f = def f3(x, y):
SyntaxError: invalid syntax

This last example resembles the concept of the anonymous function syntax chosen in Lua. First a look on how a normal function is defined in Lua. Its not that different from the Python version.

> function f1(x, y)
>>   return x + y
>> end
> print( f1(1, 2) )

Like in Python, functions are first class objects in Lua and thus also supports aliasing functions.

> f = f1
> print( f(1, 2) )

The syntax for anonymous function in Lua differs not much for how normal functions are defined. The function name is omitted (hence anonymous) and secondly the function definition is wrapped in parentheses.

> f2 = (function(x, y)
>>   return x + y 
>> end)
> print( f2(1, 2) )
> -- Or as one-liner if preferred
> f2 = (function(x, y) return x + y end)
> print( f2(1, 2) )

In Lua a function is a function and defined as such – being anonymous or not. I think this approach is more elegant that using a dedicated lambda keyword.

1 Comment

xmonk · 2008-03-31 at 4:43

I don’t know much of Python, I’m sure they got the idea from lisp. How ever I do find it kind of strange that they don’t allow direct assignment.

In Lisp, lambda is basically used for the same as in Python, but with Lisp you have the ability to assigning it to a variable for latter referencing, as well as being able to return a function (anonymous or not).

I’m sure they will probably add more functionality, and make it more like Lisp or Lua, as it makes sense, and makes it more usable feature.

I like your blog, will add it to my blogroll.

Comments are closed.