lambda expressions

Gerson Kurz gerson.kurz at
Sun Feb 3 15:55:16 CET 2002

On 03 Feb 2002 15:35:37 +0100, Martin von Loewis
<loewis at> 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
>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]:

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
- 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:

So, I see few limitations in the current implementation of lambda for
the DEDICATED lambda-user. 

More information about the Python-list mailing list