Generator (computer programming): Difference between revisions

Content deleted Content added
m Robot-assisted disambiguation (you can help!): Python programming language
m article structure
Line 2:
 
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]]. A generator is very similar to a function that returns an array, in that a generator has parameters, can be called, and generates a sequence of values. However, instead of building an array containing all the values and returning 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]].
 
== History ==
 
Generators first appeared in [[CLU programming language|CLU]] (1975)<ref>{{cite web
Line 22 ⟶ 24:
| accessdate = 2006-10-10
}}</ref>. (In CLU and C#, generators are called ''iterators''.)
 
==Uses==
 
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,
Line 29 ⟶ 33:
 
In the presence of generators, loop constructs of a language can be reduced into a single loop ... end loop construct; all the usual loop constructs can then be comfortably simulated by using suitable generators in the right way.
 
===Python===
 
An example Python generator: