4 ms·
> I am a little confused why this is regarded as a powerful pattern The power of the generator is that, unlike an iterator, the collection of values doesn't "e
by cratermoon 3y ago
> I am a little confused why this is regarded as a powerful pattern
The power of the generator is that, unlike an iterator, the collection of values doesn't "exist", it is created on the fly. This comes in to play when iterating over, say the set of integers, or something else that would take significant amounts of memory.
Also, as functions, generators can be passed around in any language that treats functions a first-class types.
- redditor98654 3y agoEven in the iterator implementation, the values are created on the fly, correct? What is an example, where a generator would be able to dynamically produce the values while an iterator would need all the source value to exist in some memory?
- cratermoon 3y agoAll generators are iterators. Not all iterators are generators.
- redditor98654 3y agoSorry for being thick. You said: The power of the generator is that, unlike an iterator, the collection of values doesn't "exist", it is created on the fly. What is a specific example where this is true?
- cratermoon 3y agoPython: <https://wiki.python.org/moin/Generators https://wiki.python.org/moin/Generators> Javascript: <https://www.digitalocean.com/community/tutorials/understanding-generators-in-javascript#infinite-data-streams https://www.digitalocean.com/community/tutorials/understandi...> The Python example is more to the point. The Javascript one gets there, but goes in a roundabout way.
- redditor98654 3y agoI still don't see where the iterator version would need to have all the values already exist but thanks for the links. To me it seems the benefit is conciseness of the implementation and its usage at the call site.