Generator (computer programming): Difference between revisions

Content deleted Content added
DPoon (talk | contribs)
Mention that Ruby also supports generators
Ruby does not support generators directly
Line 3:
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]].
 
Generators first appeared in [[CLU programming language|CLU]] (1975) [http://www.lcs.mit.edu/publications/pubs/pdf/MIT-LCS-TR-561.pdf] and are now available in [[Python programming language|Python]], [[Ruby programming language|Ruby]], and [[C Sharp|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 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,