FANDOM


A generator is a method that iterates through a collection and returns its elements one at a time, as opposed to returning all of its elements at once.

Generators yield the values of the collection one at a time, functioning as an iterator over the collection. Programming languages usually implement this using a yield statement, so that the containing method returns an iterator. Whenever the yield statement is encountered, the method breaks and returns an item from the collection. When a signal to move to the next item is encountered, the method resumes starting from the previously broken yield statement. When the generator returns or ends, the iteration ends (there are no more items in the collection).

Generators can also be implemented using first-class continuations.

Languages which offer this feature include JavaScript 1.7, Python, and Ruby.

ExampleEdit

A simple generator for a linked list using a yield statement:

iterator(list)
    current = list.head
    do
         yield current.value
         current = current.next

An implementation of a preorder traversal:

iterator(node)
    if node is null then
        return {}
    for each item in iterator(node.left)
        yield item
    for each item in iterator(node.right)
        yield item
    yield node

Ad blocker interference detected!


Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.