Search code examples
c++pythonprogramming-languageslisp

Python generators in various languages


How do you emulate Python style generators in your favorite language? I found this one in Scheme. It must be interesting to see other implementations, especially in those languages that don't have first-class continuations.


Solution

  • Here is an example in C++ that simulates generators using fibers:

    Yield Return Iterator for Native C++ Using Fibers

    The "yield return" iterator is a language feature that was created for one reason: simplicity. It is generally much easier to iterate across whole collectionl, storing all context needed in local variables, rather than crafting a complicated, custom iterator object that stores its state across subsequent retrieval operations.

    There are also the primitive C routines setjmp, longjmp to achieve similar results.
    (Lua coroutines are implemented with the above method)