Generator (computer programming): Difference between revisions

Content deleted Content added
m General fixes and Typo fixing, typo(s) fixed: For example → For example,, a infinite → an infinite using AWB
m top: clean up; http->https (see this RfC) using AWB
Line 3:
{{Refimprove|date=July 2007}}
 
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]]. In fact, all generators are [[iterator]]s.<ref>httphttps://stackoverflow.com/questions/1022564/what-is-the-difference-between-an-iterator-and-a-generator</ref> 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 can be implemented in terms of more expressive [[control flow]] constructs, such as [[coroutine]]s or first-class [[continuation]]s.<ref>{{cite web
Line 11:
| title = General ways to traverse collections in Scheme
| url = http://okmij.org/ftp/Scheme/enumerators-callcc.html
}}</ref> Generators, also known as semicoroutines,<ref name="Ralston2000">{{cite book|author=Anthony Ralston|title=Encyclopedia of computer science|url=httphttps://books.google.com/books?id=yQ9LAQAAIAAJ|accessdate=11 May 2013|year=2000|publisher=Nature Pub. Group|isbn=978-1-56159-248-7}}</ref> are a special case of (and weaker than) coroutines, in that they always yield control back to the caller (when passing a value back), rather than specifying a coroutine to jump to; see [[Coroutine#Comparison with generators|comparison of coroutines with generators]].
 
==Uses==