Generator (computer programming): Difference between revisions

Content deleted Content added
Most (all?) modern languages don't strictly limit generator usage to loops, anymore.
more intuitive explanation in first para; cite CLU, not Sather
Line 1:
[[pl:Generator (informatyka)]]
In [[computer science]], a '''generator''' is a special [[subroutine|routine]] that can be used to control the [[iteration]] behaviour of a [[control flow#Loops|loop]]. TheA conceptgenerator wasis inventedvery forsimilar theto [[Sather]]a programmingfunction languagethat butreturns itan array, in that a generator has alsoparameters, beencan incorporatedbe incalled, and generates a sequence of values. However, instead of building an array containing all the [[Pythonvalues programmingand languagereturning them all at once, a generator yields the values one at a time, which requires less memory and allows the caller to get started processing the first few values immediately. In short, a generator ''looks like'' a function but ''behaves like'' an [[iterator]].
 
Generators first appeared in [[CLU]] (1975) [http://www.lcs.mit.edu/publications/pubs/pdf/MIT-LCS-TR-561.pdf] and are now available in [[Python programming language|Python]] and [[C#]]. (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 [[parameter (computer science)|arguments]] bound to the corresponding [[parameter (computer science)|parameters]]. 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 a 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,