Jun-08-2021, 06:54 AM
Let's think easy case. Use the map function like this:
This gives us an iteratable object. To process this:
gives us a boring result, or a list
.
The equivalent way by using list comprehension is simply this one.
The list comprehension seems to compress the map function with lambda into a simple list form.
However, here is the problem.
Let's say if we want to get something closure-d, the literal way to use the map function is:
and, we can get its result like this:
This is like a lazy evaluation. Each element of the test is like a promise, which SICP tells us.
However, the may-be-equivalent list comprehension version gives us a weird result.
Wow. What we expect to get is a list [1, 2, 3], but it gives back a list [3, 3, 3].
Is this a sort of bug, or there a detailed specification?
I'm stuck with it.
Thanks, regards.
1 |
test = map ( lambda x: x, [ 1 , 2 , 3 ]) |
1 |
[i for i in test] |
1 |
[ 1 , 2 , 3 ] |
The equivalent way by using list comprehension is simply this one.
1 |
[ lambda x: x for x in [ 1 , 2 , 3 ]] |
However, here is the problem.
Let's say if we want to get something closure-d, the literal way to use the map function is:
1 |
test = map ( lambda x: lambda : x, [ 1 , 2 , 3 ]) |
1 2 3 |
>>> [i() for i in test] [ 1 , 2 , 3 ] >>> |
However, the may-be-equivalent list comprehension version gives us a weird result.
1 2 3 4 |
>>> test = [ lambda : x for x in [ 1 , 2 , 3 ]] >>> [i() for i in test] [ 3 , 3 , 3 ] >>> |
Wow. What we expect to get is a list [1, 2, 3], but it gives back a list [3, 3, 3].
Is this a sort of bug, or there a detailed specification?
I'm stuck with it.
