[Python-Dev] Re: PEP 276 Simple Iterator for ints

Skip Montanaro skip@pobox.com (Skip Montanaro)
Fri, 16 Nov 2001 13:37:53 +0100


    Skip> I liked "for i in 10:" at first, however, the more I see of the
    Skip> Haskell iterator syntax, the more I like it.
    ...
    Skip> I would tend to view the int-as-iterator as a wart (a neat sort of
    Skip> wart, but a wart nonetheless), while the Haskell syntax is elegant
    Skip> and seems to fit in well with existing Python usage.

    ...

    mal> Skip, could you tell us more about the Haskell syntax for these
    mal> things ?

I'll restrict this followup to python-dev.  The Haskell syntax has been
bandied about on c.l.py for the past several days, so I assume those folks
already know this or don't care. ;-)

Haskell has a list constructor that maps pretty nicely onto Python's range()
and xrange() functions:

    [ exp1 [, exp2] .. [exp3] ]

Since Haskell is lazy in its evaluation, infinite sequences can be
constructed easily:

    [ 0 .. ]                    # all natural numbers

More common usage in Python would be something like

    [ 0 .. 5 ]                  # [0, 1, 2, 3, 4, 5]

or

    [ 0, 3 .. 27 ]              # xrange(0, 28, 3)

I believe (Tim can correct me if I'm wrong), but when you use these
constructors to build finite sequences, they are closed at both ends, just
as Python lists, and unlike [x]range(), hence the different endpoints in the
last example.  This seems to be a sticking point for people on c.l.py who
see the lack of complete equivalence with [x]range as a problem.  I see them
as (effectively) list constructors, and expect them to be closed at both
ends.  (Though readers of this thread on c.l.py will notice that I muffed
that bit there as well. ;-)

I see a few advantages to this list constructor over [x]range():

    * I think it would be a bit easier to explain to new users than range.
      I think most people have seen sequences in math like

          [ x , x , ... , x  ]
             1   2         n

      and would thus find the notation familiar.  Admittedly, [x]range()
      isn't that difficult, however.

    * It would expose potentially significant optimizations that can't be
      made today by eliminating the attribute lookup and function call to
      range, and thus getting rid of that little bit of dynamism nobody ever
      uses anyway.

    * I think we could easily extend the notation to build sequences of
      other basic types: floats and single-character strings being the most
      obvious:

          [ "a", "c" .. "z"]

          [ 0.0, 0.1 .. 2*math.pi ]

Python already has a "..." operator, so I would propose that be used instead
of Haskell's "..".

Skip