Negative array indices

Ka-Ping Yee ping@lfw.org
Wed, 14 Oct 1998 23:43:50 -0700 (PDT)


On Thu, 15 Oct 1998, Tyler Close wrote:
> A while back, Ping and Mark were considering accepting negative array
> indices as counting from the back of the array rather than the front.
> 
> I would like register a protest. I think this cuts down on your ability to
> catch programming errors.

It is true that allowing negative indices may mask some bugs -- however,
it's a question of weighing how often that is likely to occur against
how often it will be convenient to be able to index from the back.

Python has managed for a number of years now quite happily with the
negative array indices, and the masking issue comes up rarely enough
that no one seems to mind.  In my own experience -- so far, anyway --
this masking issue hasn't been a problem for me, and i am very
grateful for the extra flexibility i get.

(By the way, i realized just a little while ago that Python calls its
only floating-point type "float", and uses double-precision numbers
for this type.  I have never seen or heard anyone question or
complain about this particular decision.)

> Also, people often use -1 as a "not found" return
> value when searching an array for a value.

True... but perhaps this will be less prevalent now that one can
return "null" or raise an exception.

>    static public String aan(String rec) {
>        if (rec.length() >= 1 && "aeiou".indexOf(rec.charAt(0)) != -1) {
>            return "an " + rec;
>        } else {
>            return "a " + rec;
>        }

This becomes:

    define aan(rec) {
        if (rec size > 0 && "aeiou" asSet maps(rec[0])) {
            "an " + rec
        } else {
            "a " + rec
        }
    }

or perhaps:

    ...
        if (rec size > 0 && rec[:1] <= "aeiou" asSet) {
    ...

or, if there are such methods:

    ...
        if (rec size > 0 && "aeiou" find(rec[0]) != null) {
    ...
    
    ...
        if (rec size > 0 && "aeiou" contains(rec[0])) {
    ...


In Perl, for comparison:
 
    ...
        if ($rec =~ /^[aeiou]/)
    ...

Well, that's a special advantage.  Without regular expressions:

    ...
        %vowels = ('a', 1, 'e', 1, 'i', 1, 'o', 'u', 1);
        if ($vowels{substr($rec, 0, 1)})
    ...

I'm surprised at it myself.  That's the shortest thing i could
come up with.  Perl is relatively feeble at string manipulation
once you take away the regular expressions.


In Python, for comparison, this is just:

    ...
        if rec[:1] in "aeiou":
    ...


In Tcl (i hardly ever use Tcl, but this is the best i could do):

    ...
        if { [lsearch {a e i o u} [string index $rec 0]] > -1 }
    ...



!ping