lambda expressions
Gerson Kurz
gerson.kurz at t-online.de
Sun Feb 3 09:55:16 EST 2002
On 03 Feb 2002 15:35:37 +0100, Martin von Loewis
<loewis at informatik.hu-berlin.de> wrote:
>I think they got introduced because some people found them convenient,
>especially those coming from a functional background. To them, it is a
>religious matter: If you have map and filter, you also ought to have
>lamba.
>
>Later, they found that, even though they got what they asked for, they
>did not get what they wanted: inside a lambda expression, you can only
>use expressions, but they also wanted anonymous code blocks.
>
>It is unlikely that they will ever get that, since nested functions
>can now refer to local variables conveniently.
Well, you can do that right now (given 2.2)! For example, take this
very useless sample code
-------------------------
a, b = 0, 10
while a < b:
print a
a += 1
-------------------------
Of course, "print range(10)" would make much more sense right here;
but for the sake of this example lets look at this small loop. OK, you
first need some auxiliary definitions:
-------------------------
import sys
# print is a statement, not a function, so we define our own
print-like function
OUT = lambda *args:sys.stdout.write(" ".join(map(str,args))+"\n")
# This will make an integer expression return either 0 or 1
BOOL = lambda x: x and 1
# Will always return 0
FALSE = lambda x: 0
# WHILE x() evaluates to true, execute y()
WHILE = lambda x,y: BOOL(x()) and (FALSE(y()) or WHILE(x,y))
-------------------------
Now, we can write the above code simply as
-------------------------
w = lambda x=[10,0]:
WHILE(lambda:(x[1]<x[0]),lambda:(OUT(x[1]),x.__setitem__(1,x[1]+1)))
-------------------------
There are some tricks involved; here are a few hints:
- a loop can be written as a recursive function (see WHILE above). You
can use this to get the REPEAT_UNTIL function I'm still missing in
python. for() is best solved by map(), and if() is just a boolean
expression.
- You need to know and love your boolean functions and, or, and not.
- if you have a block of statements you want to execute, say:
instruction #1
instruction #2
...
instruction #n
you can write that in a tuple, and (given the nature of the current
CPython) have all instructions execute in order. That is how the two
statements "print a" and "a += 1" are mapped to lambda:
(OUT(x[1]),x.__setitem__(1,x[1]+1)).
So, I see few limitations in the current implementation of lambda for
the DEDICATED lambda-user.
More information about the Python-list
mailing list