Talk:Generator (computer programming): Difference between revisions

Content deleted Content added
The emm (talk | contribs)
Line 90:
 
IMHO, unless I am required to "include" or "use" or "import" something to work with a functionality, it is supported by the language. I'd vote for including Ruby to the list of languages that support generators aka iterators. If you'd not have removed ruby twice from the language list I would simply insert it, but let's discuss this. --[[User:The emm|The emm]] 15:21, 29 August 2006 (UTC)
 
: What's happening in the Ruby example is that you're creating and passing a block into <code>countdown</code>, which calls it for each value produced, and returns once at the end. Translated to Python (with some decorator syntax abuse), this would look more or less like:
 
<blockquote>
<blockquote>
<pre>
from functools import partial
 
@partial(partial, partial) # curry countdown
def countdown(n, block):
while 0 <= n:
block(n)
n -= 1
 
@countdown(10)
def receive(count):
print count
if count == 3: print 'Ignition!'
if count == 0: print 'Liftoff!'
</pre>
</blockquote>
</blockquote>
 
: By contrast, generators are called, and return/yield to their caller (which might be somewhere different each time), for every value they produce. This means they can yield infinite sequences, and be composed together, passed around, and partially consumed, without worry. To try and illustrate:
 
<blockquote>
<blockquote>
<pre>
def count():
"""Generate all the natural numbers."""
n = 0
while True:
yield n
n += 1
 
def divisible(seq, n):
"""Yield all items from seq that are divisible by n."""
for x in seq:
if x % n == 0:
yield x
 
>>> evens = divisible(count(), 2)
 
>>> from itertools import islice
>>> list(islice(evens, 5)) # pull 5 items from evens
[0, 2, 4, 6, 8]
 
>>> for n in evens:
... if n < 20:
... print n,
... else:
... break
...
10 12 14 16 18
>>>
</pre>
</blockquote>
</blockquote>
: --[[User:Piet Delport|Piet Delport]] 12:28, 30 August 2006 (UTC)