-
damn, you start thinking 'wow a new kewl feature that does not break anything' and suddenly stuff is broken. Life just sux
-
[not tested]
def sieve2(stream):
newstream = lambda p,stream: (n for n in stream if p(n))
while 1:
head = stream.next()
yield head
p = lambda a, b=head: not divisible(a, b)
stream = newstream(p,stream)
Genexp are meant to be passed to a function for
immediate consumption, at least for Guido.
So this is beyond that scope.
That this problem would show up in this kind of usage was known. Lambda itself has a similar problem (workaround b=head).
Other capture rules were also suggested.
The PEP tracks some of this.
-
""" damn, you start thinking 'wow a new kewl feature that does not break anything' and suddenly stuff is broken."""
It doesn't break existing code, AFAIK...
And yes, this was a known problem, but nevertheless it's a bit disappointing, that genexps cannot be used for this purpose. Not that it's really important, but this lazy name lookup rule makes it difficult to do interesting stuff with genexps.
-
Just looking at the first example, in python2.3 you can already get essentially the same functionality:
import itertools
odd_numbers = itertools.ifilter(lambda x: x%2, numbers())
Consequently, I don't really see the need for generator expressions...
-
All in all the following version is not bad, I think:
def sieve3(stream):
def newstream( head, stream):
return (n for n in stream if not divisible(n, head))
while 1:
head = stream.next()
yield head
stream = newstream(head, stream)
Groetjes!
-
Oops,
sieve 2 ( and 3 ) non recursieve ???
Try calculating the first 1000 primes!
RuntimeError: maximum recursion depth exceeded
Groetjes!
-
Hm, yes, they are just as recursive... except in Scheme-land (where the original examples came from) this is considered "iterative". I guess it doesn't make much difference for Python.
-
This blog entry might be useful: http://goldenspud.com/webrog/archives/2004/09/12/ah-so-thats-how-they-work/
Maybe you could adapt it to use that (admittedly hackishly ugly) trick?
-
i\'m liked :)
-
hi friend, it seems that i am in different site,
oh no its the same site where I wanna go but no comments
are appearing here related to the topic. May be I am wrong
but friend got your site while searching blog in search
engine and it is nice to say that i visited ur site
in my friend's house who is layout controller
of website's. He told me that this particular
site contain reasnable layouts and good contents
which is relevant to this site. Rarely we get this
type of site. Really appreciates your blog page. Thnks.