Negative array indices

Dan Bornstein danfuzz@milk.com
Thu, 15 Oct 1998 11:50:21 -0700 (PDT)


Douglas Crockford writes:
>Negative indices are desirable in a scripting language and undesirable in an
>application or system language. There may be some syntactic rat poison that
>works for both, such as
>
>   Object fromBack := foo[$ index]
>
>where '[$' expands into '[foo.length -' . This is stuff that might better be
>handled by the text editor in the console window than by the language.

I'll have to disagree with Doug's assertion about what is
desirable/undesirable int a scripting/application language, but I'll draw
the same conclusion:

What I think is undesirable is *inadvertent* wraparound, in any kind of
language. If indexing innately has the negative-index "feature" then you
have to make explicit checks to avoid it if you're being paranoid, which is
probably a Bad Thing (see previous oblique references to "poka yoke").

The question becomes whether or not it's genrally useful to be able to use
an index which is not a priori known whether or not it is negative. My
guess is that the answer is no--I'll be programming with a variable which I
know is supposed to be indexing from the start or which I know is supposed
to be indexing from the end.

So, if you mean from the front, you just do the standard indexing syntax.
And if you mean to index from the back, you use the index-from-the-back
syntax (or the raw "[foo.length - n]" form if there is no sugar). Both
of these forms should throw exceptions if the index is out of bounds.

Make sense?

-dan