Hacker News new | ask | show | jobs
by noneeeed 456 days ago
I've always appreciated Ada's approach to arrays. You can create array types and specify both the type of the values and of the index. If zero based makes sense for your use, use that, if something else makes sense use that.

e.g.

  type Index is range 1 .. 5;
  type My_Int_Array is
     array (Index) of My_Int;
It made life pretty nice when working in SPARK if you defined suitable range types for indexes. The proof steps were generally much easier and frequently automatically handled.
4 comments

Many BASIC dialects had this too, which could make some code a bit easier to read e.g.

    DIM X(5 TO 10) AS INTEGER
I recall in one program I made the array indices (-1 TO 0) so I could alternate indexing them with the NOT operator (in QuickBASIC there were only bitwise logical operators).
On the other hand, if you receive an unconstrained array argument (such as S : String, which is an array (Positive range <>) of Character underneath), you are expected to access its elements like this:

    S (S'First), S (S'First + 1), S (S'First + 2), …, S (S'Last)
If you write S (1) etc. instead, the code is less general and will only work for subarrays that start at the first element of the underlying array.

So effectively, indexing is zero-based for most code.

I think lower..higher index ranges for arrays were used in Algol-68, PL/1, and Pascal long before Ada

At least in standard Pascal arrays with different index ranges were of different incompatible types, so it was hard to write reusable code, like sort or binary search. The solution was either parameterized types or proprietary language extensions

Pascal has it too.