3 ms·
Strictly speaking, there's no reason anyone "needs" generator functions. Instead of pausing the function execution at each `yield` statement, you can just write
by whycombinetor 4y ago
Strictly speaking, there's no reason anyone "needs" generator functions. Instead of pausing the function execution at each `yield` statement, you can just write a regular (non-generator) function that returns a struct including all the local variables used in the function, and repeatedly call the function with the returned struct as the first argument (or `reduce`). Admittedly this is just writing the exact mechanism of yield in a different way just to avoid using `yield`, but that's the point, it's not necessary to have it built in to the language.
- stevewatson301 4y agoFor anyone trying to get a better idea of what parent means, the PHP Generators RFC[1] shows the equivalence between generators and iterators. Iterators are what OP means by "struct including all the local variables used in the function". [1] https://wiki.php.net/rfc/generators https://wiki.php.net/rfc/generators
- int_19h 4y agoIn a similar vein, closures are not necessary, since they can always be emulated by a global function with a data object to bundle captured state - which is still the usual way to do it in C, for example. But this sort of thing gets real awkward real fast if you do it a lot. Same thing with explicit iterators vs generators.
- lmm 4y ago> they can always be emulated by a global function with a data object to bundle captured state Only if you already have the infrastructure in place to pass that captured state through to where it's needed. For a C example, you can't (safely) use an "emulated closure" with qsort (e.g. if you want to write a function that takes a list and an integer, and sorts the list modulo that integer), because you have no way to pass the data object through.