Why can’t for-of be applied to iterators?
wingo at igalia.com
Tue Jun 11 02:34:09 PDT 2013
On Tue 11 Jun 2013 11:08, Axel Rauschmayer <axel at rauschma.de> writes:
> The idea that iterators return themselves from their @@iterator
> (__iter__) hook has years of actual programmer mileage in Python. I
> take that experience seriously, compared to arguments from purity
> that tax the common use-cases.
> I’d be happy with either solution, but let’s compare:
> AFAICT, the tax is on for-of (and Array.from()): they need to
> additionally check whether an object is an iterator.
So, my proposal would be to make the for-of RHS expect an iterator, and
remove the concept of "iterable". So there's no need to check for
anything; you just assume you have an iterator.
I don't find the cost of this change (let's not say "tax" ;) terrible:
for (x of y.values()) f(x);
for (x of values(y)) f(x);
not adding more prototype methods, in favor of using modules instead. I
don't have a @horse_js in that race though.
The reason I think this is OK is because:
for (x in y) f(x)
for (x of keys(y)) f(x)
so to me it is natural that values should also come from a
for (x of values(y)) f(x)
As iterators and for-of become more prevelant, I think there are
actually few times that you want the default iterator -- the reason
being that you will deal more with iterators and less with reified
containers like arrays. The evolution of Python seems to show this, and
(dare I mention it?) Dart also seems to be going in this direction.
So that's the "cost" side. The benefit of expecting the RHS to be an
iterator is that itertools-like combinators become easier to write, and
that can only be a good thing, as we avoid making intermediate garbage
containers and eager computation. As a side benefit, we could remove
the concept of "iterable" from the spec. Also we remove the opaque
@@iterator call from for-of, which can have better error-reporting
Again, MHO :)
More information about the es-discuss