En Wed, 07 May 2008 18:38:15 -0300, globalrev <[EMAIL PROTECTED]> escribió:

i have a rough understanding of lambda but so far only have found use
for it once(in tkinter when passing lambda as an argument i could
circumvent some tricky stuff).
what is the point of the following function?

def addn(n):
                return lambda x,inc=n: x+inc

lambda is just a shortcut for defining a function without a name.
The above code is the same as:

def addn(n):
    def inner(x, inc=n):
        return x+inc
    return inner

It should be clear now that addn returns a function. addn is a "function factory": builds functions by request. You ask it "give me a function that adds 5" and addn returns that function.

if i do addn(5) it returns

addn(5)
<function <lambda> at 0x01D81830>

If you try the other version, you would get:

<function inner at 0x00A3B970>

It's the same thing, except that lambda has no name.

ok? so what do i write to make it actually do something.

adder5 = addn(5)
adder5(3)
-> 8

 and is the
inc=n necessary i cant do x+n?

Yes, you can, but there is a subtle difference that's hard to explain, and in this case it's absolutely irrelevant. Using inc=n "does the right thing" as it's a bit more efficient too.

--
Gabriel Genellina

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to