Questions/issues regarding generators

Brendan Eich brendan at mozilla.com
Thu Mar 14 15:38:29 PDT 2013


Andreas Rossberg wrote:
> On 14 March 2013 22:54, Brendan Eich<brendan at mozilla.com>  wrote:
>> Consider:
>>
>>      var i = getSomeIterator();
>>      var x0 = i.next(), x1 = i.next(), x2 = i.next();
>>      for (let x of i) {
>>          ...
>>      }
>>
>> Should the loop iterate over x0, x1, and x2? That's what would (have to)
>> happen if i[@iterator]() returned a cloneof the iterator ireset to the
>> starting "position".
>
> I agree this is an unsatisfactory consequence to the
> generatorObject.iterator = cloning proposal, which was meant as a kind
> of have-your-cake-and-eat-it-too compromise. It doesn't really achieve
> that, so I withdraw it.

Thanks.

> That leaves my original proposal not to have generator application
> return an iterator, but only an iterable. Under that proposal, your
> example requires disambiguation by inserting the intended call(s) to
> .iterator in the right place(s).

That's horribly inconvenient. It takes Dmitry's example:

  function* enum(from, to) { for (let i = from; i <= to; ++i) yield i }

  let rangeAsGenerator = enum(1, 4)
  let dup = zip(rangeAsGenerator, rangeAsGenerator)  // Oops!

which contains a bug under the Harmony proposal, to this:

  function* enum(from, to) { for (let i = from; i <= to; ++i) yield i }

  let rangeAsGenerator = enum(1, 4)
  let dup = zip(rangeAsGenerator[@iterator](), 
rangeAsGenerator[@iterator]())

which while it works, is just silly given JS's mutable object heritage. 
Programmers will not write this. They will instead write

  function* enum(from, to) { for (let i = from; i <= to; ++i) yield i }

  let dup = zip(enum(1, 4), enum(1, 4))

which is clearer, shorter, and more truthful and beautiful.

You seem to think iterables are immutable, or something. 'taint so -- JS 
is not ML! :-P

/be




More information about the es-discuss mailing list