CSC/ECE 517 Summer 2008/wiki1 2 acmoore2
Insert non-formatted text here</nowiki>Ruby, like Java, has iterators to facilitate doing operations on each member of a set. Python has generators as well. Describe how generators differ from iterators, and find examples of code sequences using generators that would be awkward with iterators.
Iterators Defined
Any computer programmer with experience has realized the power of an iterator. As defined by Wikipedia.com an iterator is "an object which allows a programmer to traverse through all the elements of a collection, regardless of its specific implementation." <1>
Generators Defined
As we have seen with iterators, the ability to traverse through a set or collection is basic need of any programming language. As described in the wiki question, Python uses a variation on the iterator and uses generators. Wikipedia.com defines generators as "a special routine that can be used to control the iteration behaviour of a loop." <2> A generator has many characteristics of that of a function that returns an array. A generator can have parameters, it can be called, and in return it returns a sequence of values. <2> The differnce from a generator and any other function that returns an array is that the generator is used to return the results one at a time, allowing it to act as an iterator. Python.com cites several benefits behind a generator. One improved area is the efficiency of memory use. The generator requires less memory by not having to store and send an entire collection or array rather passing one value at a time. <3> Another benefit cited by Python.com is high performance. Like an iterator, a generator returns one value at a time allowing for a process to start accessing the data earlier and faster than it would if it had to wait for the entire array to return. <3>
<1> http://en.wikipedia.org/wiki/Iterator#Iterators_in_different_programming_languages
<2> http://en.wikipedia.org/wiki/Generator_%28computer_science%29