3 ms·
The last item of an array should be simply arr[-1]. This is very easy to understand once you have played with it for a few days. Your second example isn’t ulti
by jacobolus 10y ago
The last item of an array should be simply arr[-1]. This is very easy to understand once you have played with it for a few days.
Your second example isn’t ultimately about array indices, but is caused by confusion between using 0 as both an ordinal number and as a representation of boolean false.
- int_19h 10y agoThe problem with this is that it breaks the conceptual model of zero-based indexing - your indices start from 0 when counting from the left, but from (-)1 when counting from the right! It always irked me in Python. This is especially painful if you need to do further arithmetic on the indices in a single slice operation, because you have to remember the different rules at play here. With 1-based indexing, you can just skip zero, and be consistent - a[1] is the first element from the left, a[-1] is the first element from the right.
- jacobolus 10y agoThe “conceptual model of zero-based indexing” is: use the left fencepost as the index. This is consistent and easy to reason about. With one-based indexing, you can’t have arr[-1] as the last element (that would cause huge problems!). Languages with one-based indexing write something like arr[end] or arr[arr.length] to refer to the last element, with arr[end-1] or arr[arr.length-1] referring to the second-to-last element.
- int_19h 10y ago> With one-based indexing, you can’t have arr[-1] as the last element (that would cause huge problems!) Can you give some examples?
- benlorenzetti 10y agoI agree with you but wouldn't the first element from the right be a[-0], sort of an abuse-of-notation for a[N-0]?
- int_19h 10y agoIt could, if you could distinguish positive and negative zero for integers.
- Normal_gaussian 10y agoThe index a[b] in languages with safe bounding can be thought of as a[(a.length + b) % a.length]. Modulo and exponents are, to me, the primary reason for using a 0 based numbering system