Check out Dart's iterators

Jason Orendorff jason.orendorff at gmail.com
Sun Feb 10 13:55:05 PST 2013


On Sun, Feb 10, 2013 at 1:55 PM, Oliver Hunt <oliver at apple.com> wrote:

> I do dislike the exception based termination, I _think_ i'd prefer next()
> and hasNext() style iteration over exceptions, especially given that for
> the most part these are hidden by clean syntax.


Yuck. Python's iterator protocol may be a bit ugly to consume, but it is
nicer to implement than next/hasNext. (moveNext/current also seems a little
easier to implement than next/hasNext.)

It turns out (at least in Python) that while you rarely have to directly
implement the raw iterator protocol, you seriously almost *never* have to
directly consume it. So it was the right design decision, in Python at
least, to optimize the protocol for ease of use on the *implementing* side.

For example. In Python, file objects are iterators. It works like this
(only actually this is implemented in C, not Python):

    class file:
        ...
        def __iter__(self):
            return self

        def next(self):
            line = self.readline()
            if line == '':
                throw StopIteration
            return line
        ...

It's nice that the iterator protocol does not require the iterator to store
the value across method calls, from hasNext() to next(). It's kind of nice,
generally, not to have to worry, in the implementation of hasNext(), about
whether or not next() was called since the last time hasNext() was called.

Probably all this is down in the noise though.

> My personal concern with all of these is how they deal with nested
iterators.

I see you've already taken this back, but here's what my answer would've
been:

    def iter_tree(node):
        if node is not None:
            for v in node.left:
                yield v
            yield node.value
            for v in node.right:
                yield v

The low-level protocol just doesn't enter into it. The real APIs for
working with Python iterators are yield, for-in, and itertools.

-j
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20130210/6424194e/attachment.html>


More information about the es-discuss mailing list