[Tutor] Why use lambda?
Alan Gauld
alan.gauld at btinternet.com
Sat Aug 2 19:00:30 CEST 2008
"desmond mansfield" <desm at hotmail.co.uk> wrote
> But what I don't understand, and cannot seem to find an
> answer to, is why I'd actually want to use it ?
Its a matter of taste. There is nothing you can do with
lambda that you cannot do with a function definition.
But you might need an awful lot of functions which can
make your code cluttered.
> What can lambda do that normal function definitions cannot?
Exist without a name.
> Is it quicker to execute/less memory intensive?
No.
> Or is it just quicker to type and easier to think about?
Quicker to type but most folks don't find them easier to think about!
The exception to that is people trained in Lambda calculus where
lambdas are a fundamental part of the theory. Using lambdas
then becomes the natural way to express a solution. Lambda
calculus is what the Functional Programming style is based upon.
Python supports FP so it has lambdas. You don't have to use them.
Some other languages provide much stronger support for lambdas
than does Python. The python community tends to be split
into those who would like to see lanmdas made much more
powerful and those who woyuld like to see them removed
entirely! The current syntactic sugar version pleases nobody
very much. :-)
>From a pure FP theory point of view a function is a named
lambda. In some dialects of Lisp you define a function by
creating a lambda, like this:
(defun f
(lambda (expr)))
In Python we can say that
def f : return (expr)
is identical to
f = lambda: (expr)
Ruby and Smalltalk both offer "code blocks" which perform the
same function but with more flexibility.
--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld
More information about the Tutor
mailing list