Pyli/Generators

From Jonathan Gardner's Tech Wiki
Jump to: navigation, search
Top: Pyli
Up: Pyli
Prev: Pyli/async
Next: ???

Generators

A generator is a special function. On the outside, it is an iterator. On the inside, it is programmed in a serial way to yield certain values.

Python has these and they are really, really nice.

To write a generator, use the gen method.

  • (gen (params) body...): Defines a generator function. (Compare with fn and macro.) This will return a new function.
  • (def-gen name (params) body...): Defines a generator method and makes it a global.

A call to a generator will yield a Pyli/Types/Gen-Iter. A call to next on this will cause the body to be executed, until the yield function is called. When this is called, the value is passed as the result of next. If the generator returns, or the body is completely exhausted, then Stop is signalled.

Generator Syntax

Python's generator syntax is very handy. Note that this is rolled into for when yield statements are used.