functional vs procedural list comprehension
Peter Dobcsanyi
petrus at pobox.com
Mon Sep 10 06:15:14 EDT 2001
Guido and Tim pointed out that the implementation of a functional
listcomp would be more difficult and I must accept that if they say so :-)
However, I am still not convinced that the current listcomp's semantics
is easier to explain or more consistent semantically than a functional
one. To me, the way we use a listcomp suggest that it acts like a
function, that is it returns a list. For example:
print [ {expr_of_x} for x in xs if {logexpr_of_x} ]
new_list = [ {expr_of_x} for x in xs if {logexpr_of_x} ]
for item in [{expr_of_x} for x in xs if {logexpr_of_x}]:
do_something_with(item)
But this appearance is deceptive since listcomps don't really act like
functions. The current semantics can be described (using the last
example) as:
ys = []
for x in xs:
if {logexpr_of_x}:
ys.append({expr_of_x})
for item in ys:
do_something_with(item)
...
del(ys)
(It is rather something like a result of a macro expansion.)
That is why I feel some inconsistency between the application (the way
we use it) and the semantics of listcomp.
In contrast, a functional listcomp's semantics would be:
def expr(x):
return {expr_of_x}
def pred(x):
return {logexpr_of_x}
def listcomp(expr, ls, pred):
new_ls = []
for x in ls:
if pred(x):
new_ls.append(expr(x))
return new_ls
for item in listcomp(expr, xs, pred):
do_something_with(item)
...
What is happening here can be consistently explained with the semantics
of function invocation.
Peter
More information about the Python-list
mailing list