[Python-Dev] Lukewarm about range literals

Charles G Waldman cgw@fnal.gov
Tue, 29 Aug 2000 10:29:20 -0500 (CDT)


Thomas Wouters writes:
 > On Tue, Aug 29, 2000 at 09:46:23AM -0500, Skip Montanaro wrote:
 > 
 > > Which was why I proposed "...".  It's sort of like "..", but has the
 > > advantage of already being a recognized token.  I doubt there would be much
 > > problem adding ".." as a token either.
 > 
 > "..." is not a token, it's three tokens:
 > 
 > subscript: '.' '.' '.' | test | [test] ':' [test] [sliceop]
 > 
 > So adding ".." should be no problem.

I have another idea.  I don't think it's been discussed previously,
but I came late to this party.  Sorry if this is old hat.


How about a:b to indicate the range starting at a and ending with b-1?

I claim that this syntax is already implicit in Python.

Think about the following:  if S is a sequence and i an index,

     S[i]

means the pairing of the sequence S with the index i.  Sequences and
indices are `dual' in the sense that pairing them together yields a
value.  I am amused by the fact that in the C language, 

     S[i] = *(S+i) = *(i+S) = i[S] 

which really shows this duality.

Now we already have

     S[a:b]

to denote the slice operation, but this can also be described as the
pairing of S with the range literal a:b

According to this view, the square braces indicate the pairing or
mapping operation itself, they are not part of the range literal.
They shouldn't be part of the range literal syntax.  Thinking about
this gets confused by the additional use of `[' for list construction.
If you take them away, you could even defend having 1:5 create an
xrange-like object rather than a list.

I think this also shows why [a:b] is *not* the natural syntax for a
range literal.

This is beautfully symmetric to me - 1..3 looks like it should be a
closed interval (including the endpoints), but it's very natural and
Pythonic that a:b is semi-open: the existing "slice invariance" 

     S[a:b] + S[b:c] = S[a:c] 

could be expressed as 

     a:b + b:c = a:c

which is very attractive to me, but of course there are problems.


The syntax Tim disfavored:

     for i in [:len(a)]:

now becomes

     for i in 0:len(a):  
     #do not allow elided endpoints outside of a [ context

which doesn't look so bad to me, but is probably ambiguous.  Hmmm,
could this possibly work or is it too much of a collision with the use
of `:' to indicate block structure?

Tim - I agree that the Haskell prime-number printing program is indeed
one of the prettiest programs ever.  Thanks for posting it.

Hold-off-on-range-literals-for-2.0-ly yr's,
				-C