lambda expressions

Justin Sheehy justin at iago.org
Mon Feb 4 00:45:58 CET 2002


Bas van Gils <bas.vangils at home.nl> writes:

> I've been wondering, lately, about lambda-expressions. Most programming
> languages support 

Well, most lispy languages, and a few others.

They're really useful for talking _about_ programming languages.
However, you asked about using them _in_ programming...

> I wondered why (mostly because I find them hard to read, valueing
> _readable_ code). Collegues at work couldn't give me a satisfying
> answer so ... can anyone explain to me why lambda-expressions are so
> useful?

They are extremely useful in languages designed around their use.  For
instance, Scheme wouldn't be nearly as fun without lambda.  There are
a few differences between Scheme (an example of a language where
lamdba is essential and good) and Python (where lambda is somewhat
rightfully sneered at).

In Scheme, lambda is the usual way to define a function.  In Python,
lambda is a poor cousin to "def".

The structure of Scheme is such that all functions can be described by
lambdas, whereas Python's lambda is crippled by being much more
restricted than def with regard to its body.

I could go on, but the difference basically comes down to the fact
that lambda expressions are a fundamental part of how some languages
describe functions, but in Python they clearly stand out as not
seeming much like the rest of the language as designed.

So, to answer your question: in Python, they are not really all that useful.

The times I tend to use them:

- When I want to pass a simple callback to another function or class.

- When the argument to map or filter is so simple that a lambda actually
  makes my code easier to read (for me, anyway).
 
- In debugging at the REPL.

Even in those cases, I use a named function more often than not.

-Justin

 








More information about the Python-list mailing list