Generator (computer programming): Difference between revisions

Content deleted Content added
No edit summary
m restore Python indentation to standard convention, tweak JavaScript reference's markup
Line 17:
[http://www.python.org/dev/peps/pep-0289/ PEP 289: Generator Expressions],
[http://www.python.org/dev/peps/pep-0342/ PEP 342: Coroutines via Enhanced Generators]
</ref>, [[C Sharp|C#]], and [[JavaScript]]<ref>{{cite web
| url = http://developer.mozilla.org/en/docs/New_in_JavaScript_1.7#Generators
| title = New In JavaScript 1.7
| accessdate = 2006-10-10
}}</ref>. (In CLU and C#, generators are called ''iterators''.)
 
Generators are usually [[execution (computers)|invoked]] inside loops. The first time that a generator invocation is reached in a loop, an iterator [[object (computer science)|object]] is created that encapsulates the state of the generator routine at its beginning, with arguments bound to the corresponding [[parameter (computer science)|parameter]]s. The generator's body is then executed in the context of that iterator until a special ''yield'' action is encountered; at that time, the value provided with the ''yield'' action is used as the value of the invocation expression. The next time the same generator invocation is reached in a subsequent iteration, the execution of the generator's body is resumed after the ''yield'' action, until yet another ''yield'' action is encountered. In addition to the ''yield'' action, execution of the generator body can also be terminated by a ''finish'' action,
at which time the innermost loop enclosing the generator invocation is terminated.
 
Line 30 ⟶ 34:
<pre>
def countfrom(n):
while True:
yield n
n += 1
 
# Example use: printing out the integers from 10 to 20.
Line 39 ⟶ 43:
 
for i in countfrom(10):
if i <= 20:
print i
else:
break
</pre>
 
In Python, a generator can be thought of as an iterator that contains a frozen [[stack frame]]. Whenever the iterator's <code>next()</code> method is called, Python resumes the frozen frame, which executes normally until the next <code>yield</code> statement is reached. The generator's frame is then frozen again, and the yielded value is returned to the caller.
 
Generators can be implemented in terms of more expressive [[control flow]] constructs, such as [[coroutine]]s or first-class [[continuation]]s.<ref>{{cite web
Line 69 ⟶ 73:
<references/>
 
* Stephan Murer, [[Steve Omohundro | Stephen Omohundro]], David Stoutamire and Clemens Szyperski: Iteration abstraction in Sather. ''ACM Transactions on Programming Languages and Systems'', 18(1):1-15 (1996) [http://portal.acm.org/citation.cfm?doid=225540.225541]
 
[[Category:Programming constructs]]