I sing the praises of lambda, my friend and savior!

Robert Brewer fumanchu at amor.org
Tue Oct 12 00:19:52 CEST 2004


Jeff Shannon wrote:
> Maybe I'm just ignorant or behind the times, but I still 
> haven't seen a 
> real argument as to *why* lambdas are so useful.  There's some 
> assertions about how avoiding giving something a name makes things 
> clearer, which I disagree with.  ('Explicit is better than 
> implicit.'  I 
> don't see how 'no name' makes the purpose of a code segment 
> clearer than 
> 'some meaningfully descriptive name', no matter how many times it's 
> asserted.)  There's complaints that it takes a whole two 
> extra lines to 
> type a proper function def, as opposed to being able to use lambdas 
> inline... but again, I'd claim that with a properly named 
> function, the 
> intent at point-of-use will be quite clear and the cost of two extra 
> lines of code is minimal.

All I can say is, "sometimes it's not minimal". Adapters are a great
example:

xforms = {dejavu.icontains: lambda x, y: x + " Like '%" + y[1:-1] +
"%'",
          dejavu.icontainedby: icontainedby,
          dejavu.istartswith: lambda x, y: x + " Like '" + y[1:-1] +
"%'",
          dejavu.iendswith: lambda x, y: x + " Like '%" + y[1:-1] + "'",
          dejavu.ieq: lambda x, y: x + " = " + y,
          dejavu.now: lambda: "Now()",
          dejavu.today: lambda: "DateValue(Now())",
          dejavu.year: lambda x: "Year(" + x + ")",
          }

Conciseness is a continuum. I understand (and agree with) your
contention that many lambdas wouldn't suffer from a full function
definition. Writing the above with full functions, however, would take
us to the other extreme end of the continuum, which is boilerplate for
boilerplate's sake. (If I ever write another unnecessary Java
getter/setter pair, shoot me. ;)

The other use case where I use lambdas heavily is in querying
databases*; I wrap up lambdas in an Expression object which can then be
passed around through the domain model and into the data source layer
(and can even be pickled). I chose lambdas for two reasons:

1) I admit, one-liners. But much more importantly,

2) The restricted expressivity of lambdas is a plus when using them as
queries. I purposefully don't want to have to handle multiple statements
(especially loops), nor assignment. They just get in the way. Finally,
when building such queries on the fly, I gain a bit of a security;
lambdas function like little "restricted execution" blocks.


Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org

* See the "logic" module in svn://casadeamor.com/dejavu/trunk



More information about the Python-list mailing list