3 ms·
I think seeing generators as special functions makes them feel more magic than what they really are: generators are nothing more than a syntactic sugar for obj
by littlestymaar 3y ago
I think seeing generators as special functions makes them feel more magic than what they really are: generators are nothing more than a syntactic sugar for objects with a “call” method that will change the values of the private fields in this object, that's why you can call it repeatedly with different results.
Some patterns become easier to write with the generator syntax, but it's not really adding expressive power. (Unlike futures for instance)
- heavenlyblue 3y agoYou could also have an object with on_success, on_failure attributes so Futures are the same syntax sugar
- littlestymaar 3y agoIn JavaScript, where you have first class functions and an event loop built-in, yes. But for languages that lack one of those, then no.
- btown 3y agoIMO this is like saying a high-level language is syntactic sugar for assembly. Generators allow you to write a state machine as a procedural function whose local variables are automatically suspended when you yield and restored when the caller returns control to the generator. They compile this down to, as you said, an object with a call method. But that transformation is as nontrivial as any compilation/transpilation project.