logo

Programming Languages - Generators

In Python / Ruby / JavaScript, generator functions could be written using the yield keyword provided by the language.

By Language

Python

def foo():
    yield 1
    yield 2
    yield 3
  • returns a list: [x for x in range(3)]
  • returns a generator: (x for x in range(3))

List comprehensions can cause problems for large inputs by using too much memory.

Generator expressions don’t materialize the whole output sequence when they’re run. Instead, generator expressions evaluate to an iterator that yields one item at a time from the expression.

next() will return the next value, until it is exhausted:

>>> a = (x for x in range(3))
>>> next(a)
0
>>> next(a)
1
>>> next(a)
2
>>> next(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

Generator is composable

>>> a = (x for x in range(3))
>>> b = (y for y in a)
>>> next(b)
0
>>> next(b)
1

A recursive generator that generates Tree leaves in in-order.

def inorder(t):
    if t:
        for x in inorder(t.left):
            yield x

        yield t.label

        for x in inorder(t.right):
            yield x

JavaScript

function* foo() {
  yield 1;
  yield 2;
  yield 3;
}

const gen = foo();

console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
console.log(gen.next().value); // 3

Go

No yield, could be simulated using a goroutine and a channel.