Why can’t for-of be applied to iterators?
brendan at mozilla.com
Fri Jun 14 21:23:53 PDT 2013
Claude Pache wrote:
> Yes, the name of the contract is `@@iterator`. A for/of loop is normally used to loop over an entire collection of items, so it is expected that the user provides an object from which one could extract a fresh (i.e. non-consumed) iterator. In order to enforce that requirement, one could ask iterators to remove or poison-pill its own `@@iterator` method as soon as its `next` method is called.*That* would add extra value (better error-checking) to the programmer, if we find it worth.
I've never felt the need, in JS1.7+ or Python.
> But replacing `@@iterator` with `ToIterator` is mostly changing an implementation detail.
Agreed, but see below.
>>> >> Consequently, if you want to write abstractions, you will
>>> >> likely be better off basing them on iterators, and leave iterables as
>>> >> a mere convenience mechanism for for-of loops over concrete objects.
>> > This does not follow. It flies in the face of boatloads of experience with JS and Python (itertools and beyond).
>> > I guess we are going 'round the assertion block. I've seen that building before :-|.
>> > /be
> If I want to write an abstraction in a library which loops over an entire collection (e.g,, an `Iter.reduce` function), I just invoke the `@@iterator` method to get an assumed fresh iterator (and it is the responsibility of the user to not provide me with a consumed or half-consumed iterator, unless we add the error-check I mentioned above). If we replace the `@@iterator` method call by an abstract `ToIterator` or `GetIterator` operation, there should be a, say, `Reflect.ToIterator` function that I could use in my library code.
No plan to replace -- the public symbol is simpler and avoids growing
traps and Reflect default-trap-impls like topsy.
More information about the es-discuss