A replacement for lambda

Paul Rubin http
Sat Jul 30 02:40:08 EDT 2005


James Richards <rootrot at govtabuse.com> writes:
> Personally, I can't recall any decent programmer I know who objects
> to actually writing out a variable name.  In fact, I don't know a
> single "real" programmer (this is one who writes programs he intends
> to look at again in, say, 3 weeks) who doesn't insist on writing
> "real" variable names.

The issue is whether you want to name every intermediate result in
every expression.

   sum = a + b + c + d + e

is a lot nicer than

   x1 = a + b
   x2 = c + d
   x3 = x1 + e
   sum = x2 + x3

the language has nicely kept all those intermediate results anonymous.

Python has first-class functions, which, like recursion, is a powerful
idea that takes some getting used to.  They let you say things like

  def derivative(f, t, h=.00001):   # evaluate f'(t) numerically
    return (f(t+h) - f(t)) / h
  
  dy_dt = derivative(cos, 0.3)     # approx. -sin(0.3)

With anonymous functions, you can also say:

   dy_dt = derivative(lambda x: sin(x)+cos(x), 0.3) # approx. cos(.3)-sin(.3)

Most Python users have experience with recursion before they start
using Python, so they don't see a need for extra keywords to express
it.  Those not used to first-class functions (and maybe some others)
seem to prefer extra baggage.  For many of those used to writing in
the above style, though, there's nothing confusing about using a
lambda there instead of spewing extra verbiage to store that
(lambda x: sin(x)+cos(x)) function in a named variable before
passing it to another function.



More information about the Python-list mailing list