Monday, July 30, 2012

Zero-based indexing for Vector and Univ_String

Whether array indices most "naturally" should start at zero or one remains a surprisingly unresolved question.  Algol, Pascal, Ada, Modula, Eiffel, etc. generally started array indexing at 1, or allowed the programmer to choose the bounds, while C with its model of array indexing being equivalent to pointer arithmetic, requires starting at zero since array indices are interpreted as offsets.

In ParaSail arrays are simply a special case of a container, and indexing is user-definable, so the index need not even be integers, and certainly there is no requirement that the first index be zero, or one, or any specific value.  On the other hand, there are some pre-provided modules such as Vector and Univ_String which allow indexing, and some decision has to be made about whether to start with zero or one.  Because of the Pascal/Ada/Modula heritage, the natural choice was to start with one.

However, there are algorithms where starting with zero is more natural, and there are certainly programmers who are more comfortable with starting indexing with zero, so we have recently added zero-based indexing versions of Vector and Univ_String, namely ZVector and ZString.  So using ParaSail's half-open intervals, one can loop over the contents of a ZVector (or a ZString) with:
    var ZV : ZVector<Univ_Integer> := [1, 3, 5, ...];
    var Sum := 0;

    for I in 0 ..< Length(ZV) loop
        Sum += ZV[I];
    end loop;

No comments:

Post a Comment