Day 2 meeting notes
Brendan Eich
brendan at mozilla.com
Fri Jul 30 15:35:51 PDT 2010
On Jul 30, 2010, at 3:02 PM, Oliver Hunt wrote:
> On Jul 30, 2010, at 2:56 PM, Brendan Eich wrote:
>
>> To avoid this confusion you can add new syntax (|for each| or whatever, doesn't matter). I've argued in recent posts that it is better from a global and long-term point of view to reform for-in after Python, than to condemn it and grow the language with new and generally more verbose, yet similar, syntax.
>
> It annoys me that this doesn't leave a convenient way to iterate arrays, for (... in someArray) will forever do the braindead thing.
Me too, and I've seen people (myself included) make the mistake of writing
for (i in [0,1,1,2,3,5,8,13]) ...
wanting the values not the keys.
> If we look to pythonic behaviour we see that python's for..in syntax has always iterated arrays by value rather than index.
Indeed.
> By overloading for(in) we are effectively saying that there will never be a simple way to iterate arrays by value directly, because no one can even extend the builtin array type be have a generator for iteration because doing so would be too fragile.
This "never be a simple way" is not true in JS1.7+:
js> Array.prototype.__iterator__ = function () { for (let i = 0; i < this.length; i++) yield this[i]; };
(function () {for (let i = 0; i < this.length; i++) {yield this[i];}})
js> for (v in [3,4,5]) print(v)
3
4
5
The unstratified, ugly-named __iterator__ meta-method is the getter or factory for finding or creating an appropriate iterator. I use a generator, since it is the simplest way of writing such a factory.
With Harmony we stratify such meta-programming using proxies, so you can't use the prototype chain to find the iterate handler-trap -- you must directly reference a Proxy instance after 'in' in the for-in head.
Could we "fix" Harmony to iterate values not keys for Arrays, by fiat, and say "opt-in versioning, pay this migration tax, it is worth it"? I don't think so, but we can discuss.
Perhaps there's a modular way to allow one-time, explicit opting into a mode where for-in iterates array values, not keys. The obvious criticism is modes are bad, don't add more knobs to the language.
/be
More information about the es-discuss
mailing list