Questions/issues regarding generators
allen at wirfs-brock.com
Thu Mar 7 12:58:38 PST 2013
On Mar 7, 2013, at 11:05 AM, Andreas Rossberg wrote:
> On 7 March 2013 18:30, Allen Wirfs-Brock <allen at wirfs-brock.com> wrote:
>> On Mar 7, 2013, at 7:37 AM, Andreas Rossberg wrote:
>> I'm not sure I convinced by this. An iterator instance represent a single
>> specific iteration. Your second example is really a user bug and should be
>> coded as:
>> let dup = zip(enum(1,4), enum(1,4));
>> Zip's informal contract should state that if iterators are passed as
>> arguments they need to be distinct objects. If you want to implement it
>> defensively, you can add a check for that pre-condition.
> I have to disagree here. That is just evading the question what the
> contract for .iterator is. Either it is supposed to create new state
> or it isn't. It's not a very useful contract to say that it can be
> both, because then you cannot reliably program against it. And from
> the desire to support collections as iterables it pretty much follows
> that it should create fresh state (and under that assumption, there is
> no bug in zip).
I think the meaning of @@iterator would be clearer if it was named asIterator. obj.asIterator()/obj[@@iterator]]() is a request to provide an iterator which may be either. obj itself or a new object that provides default iteration behavior for obj.
>>> The problem boils down to the question whether a generator function
>>> should return an iterable or an iterator. The current semantics
>>> (inherited from Python) tries to side-step the question by answering:
>>> "um, both". But as the example demonstrates, that is not a coherent
>> I think it is pretty clear that the current semantics is that a generator
>> function always returns an iterator.
> Well, then it should not have an .iterator method, and for-of should
> note invoke that method. But clearly, that would make it harder to use
> generators with user-defined iteration abstractions.
again, think of it as asIterator...it is coercion method, not a factory.
> But your comment about cloning actually made me think about another
> solution: you can make a generator object _truly_ both an iterator
> _and_ an iterable by defining its .iterator method to be a clone
> method. Importantly, in the normal use case (for-of), that cloning
> would not actually be observable, and could easily be avoided by an
Or, define @@terator such that it return this only on its first call and any subsequent @@iterator calls to that object does a clone (if possible). The place this would fall down is when an iterator object is passed as a parameter down through a chain of calls that do a @@iterator coercion at each step of the chain.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the es-discuss