2.3.6 Numbering a dimension from its last element
Array index values are subtly asymmetric: An index of 1 represents the first element, 2 represents the second element, 3 the third, and so on. In order to refer to the last, or next to last, or any element relative to the final element, you apparently need to find out the length of the dimension.
In order to remedy this asymmetry, Yorick interprets numbers less than 1 relative to the final element of an array. Hence, x(1) and x(2) are the first and second elements of x, while x(0) and x(-1) are the last and next to last elements, and so on.
With this convention for negative indices, many Yorick programs can be written without the need to determine the length of a dimension:
computes a point-centered estimate of the derivative of a function f with values known at points x. (A better way to compute this derivative is to use the pcen and dif range functions described below. See section Rank preserving (finite difference) range functions.)
In this example, the extra effort required to compute the array length would be slight:
However, using the negative index convention produces faster code, and generalizes to multi-dimensional cases in an obvious way.
The negative index convention works for scalar index values and for the start or stop field of an index range (as in the example). Dealing with negative indices in an index list would slow the code down too much, so the values in an index list may not be zero or negative.