4 ms·
My main issue with the start-from-0 convention is that while it makes sense if you consider an array as a pointer with more pointers coming after it, it doesn't
by LeafStorm 15y ago
My main issue with the start-from-0 convention is that while it makes sense if you consider an array as a pointer with more pointers coming after it, it doesn't make as much sense when it is simply a list of objects.
When I have a five-page document, I number the pages as one, two, three, four, five, and say that the length of the document is five pages. If I have an "empty" document (assuming such a thing makes sense in the real world), it would have length zero, and since there are no elements to assign indices to, I would not assign them numbers.
I have to admit that I much prefer the Lua convention: in a sequence of N items, they are numbered 1, 2...N-1, N. The length of the sequence is equal to the index of the last item in the sequence. "Negative" indices are treated as if one was counting backwards from the end of the sequence, such that the items are numbered -N, (-N)+1, (-N)+2...-2, -1, i.e. the spoken forms "last," "second-to-last," "third-to-last..." This means that 1 to -1 encompasses the whole sequence. This does have the unfortunate side effect that 0 refers to no item, but even when describing an array implemented as a pointer we refer not to the "zeroth" element, but to the first and the last.
This also has an added benefit that the range notation used by Lua's numeric for loops makes perfect sense when compared to the notation used by Python's range statement. In Lua,
for n = 1, #tbl
produces all of the indices in the given table, as does
for n in range(len(ls))
in Python, for a list. In Lua, this can simply produce the numbers 1, 2, 3, 4, 5, 6 for a table of six elements, which is intuitive even when using the numeric for to simply generate a series of integers:
for n = 1, 6
However, in Python, the fact that range is used to generate the indices also means that range(1, 6) produces 1, 2, 3, 4, 5 ("Where the heck is the 6?") and a simple range(6) produces 0, 1, 2, 3, 4, 5 ("Still no 6, and where did that 0 come from?") To get 1, 2...6, you need range(7) ("What does this have to do with 7?")
- masklinn 15y agoSo... you prefer Lua because half-open ranges confuse you?
- sesqu 15y agoIf we're going for half-open ranges, range(n) ≝ 0<i≤n would make more sense than 0≤i<n. But then again, sign(0) is still a point of disagreement today. Dijkstra argued against this by noting that that makes adding 0 to the range impractical, but then he was considering natural numbers, not the half-open ranges we're talking about and using notation for here. Me, I prefer integers and the a..b style, despite the off-by-one error.