Talk:Generator (computer programming): Difference between revisions

Content deleted Content added
Line 217:
::Also, generators' purpose is not to control loops. They are not to be mistaken as some sort of functional control structure! [[User:Nowhere man|Nowhere man]] 18:50, 24 April 2007 (UTC)
:::Yes, that quoted sentence is perhaps misleading in that it implies a specific implementation of generators, using iterators, which doesn't necessarily have to be true. Note though as an example, in the Python language, invoking a generator function does in fact create a real iterator object (it has a next() method, and raises a StopIteration error when/if the generator terminates). But it's not fair to say that just because that's how Python does it that it is how all languages must do it. As far as other types of generators, yes there are undoubtedly a lot of them. Most fall into the more casual use of the Engligh word ''generator'', as in something that produces something else. Many of these are listed on the [[Generator (disambiguation)]] article. It probably would be worthwhile to put a little reference to these other types someplace. In terms of the specific type of generator discussed in this article (which is iterator-like), use in loops is quite common. Although a prime number generator or random number generator could be implmented as an interator-style generator, they don't have to be as you pointed out. But that's not what this article is about. I guess we just need to tighten up some language. -- [[User:Dmeranda|Dmeranda]] 19:43, 24 April 2007 (UTC)
:::Here's a python example showing how a generator really results is a true iterator (i.e., it obeys the standard Python iterator-protocol):
<pre>
>>> def count_to_ten(n): # Define a generator function
... while n <= 10:
... yield n
... n = n + 1
... return
...
>>> gen = count_to_ten(7) # Invoke the generator
>>> gen.next() # Treat the invocation as an iterator object
7
>>> gen.next()
8
>>> gen.next()
9
>>> gen.next()
10
>>> gen.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
</pre>
[[User:Dmeranda|Dmeranda]] 19:52, 24 April 2007 (UTC)