lambda
Joey Gibson
joeyGibson at mindspring.com
Wed Mar 29 13:51:18 EST 2000
On Wed, 29 Mar 2000 10:19:04 GMT, morbid at doesnotlikespam.inet.net.nz
(Morbid Curiosity) wrote:
||| On 28 Mar 2000 22:37:53 -0800, Falknor <falknor at worldspy.net> wrote:
||| >Hmm, what exactly is the use of lambda? It just isn't clickin for
||| >some reason.... Are they just syntactical candy (such as the ternary
||| >operator ?: in C++ is syntactical candy..) or what. *ponders* Anyone
||| >who could explain it, and gimme a little example would have my thanx. :)
|||
||| Lambda functions come from a functional programming paradigm, but I've
||| found a couple of situations where they're really handy in a general
||| imperative program, too. Have a look at this code snippet:
It took me a while to 'get' lambdas at first too. They are most useful
(IMO) when paired with map(), filter() and reject(). These functions take a
function as the first argument. Using a lambda allows you to declare the
function inline as opposed to declaring the function earlier.
For example, this is applying a function to a list without lambdas:
aList = ['fred', 'ted', 'tom', 'bob', 'foo']
def myfunc(x):
return x * 2
res = map(myfunc, aList)
And here it is with lambdas:
aList = ['fred', 'ted', 'tom', 'bob', 'foo']
res = map(lambda x: x * 2, aList)
I think you can also use them as defaults arguments to functions that
need a function as a parameter.
Joey
--
-- Sun Certified Programmer for the Java2 Platform
-- Pocket Smalltalk Tutorial: www.mindspring.com/~joeygibson/st/pstIntro
--
-- "Then slew they the goats, YEA! And placed they the bits,
-- in little pots."
More information about the Python-list
mailing list