161 points · by feynma · 9y ago · 216 comments
Also, the recent rise in programming with multidimensional data invites the question of why matrix integer indices should include zero, which Dijkstra's essay doesn't address.
Likewise, the increasing use of real variables in software invites asking whether an elegant syntax for specifying integer ranges applies equally well when used for real ranges, since <= operators make less sense when constraining floats. Also not addressed.
Yes, explicit indices are less common than they used to be due to iterator support in languages. However they are far from being obsolete. I've been recently going through a lot of code dealing with numerical calculations and there you see hardly any iterator use.
Also, MATLAB code, which uses 1-based indices, is an absolute pain to deal with compared to Python/numpy, for example.
I wish I could somehow hide the fact that Lua uses 1-based indexing by concealing them completely with iterators.
And yet here I am, programming in Lua with 1-based indices in tables and dealing with the logical inconsistencies of interfacing with application bindings that necessarily expose C-native structures using 0-based indexing.
This betrays the complete lack of mathematical qualification evident in the rest of your comment. IEEE numbers don't even pretend to be the reals. The most that can be said for them is that they're two copies (positive and negative) of a very small subset of the nonnegative rationals, adjoined to a couple extra symbols (+inf, -inf, NaN), with really wonky operations to work around the obvious non-closure of the rational subsets under standard mathematical operations (let alone the approximations to transcendental functions). I think it's important to be extremely clear: this is not at all like the mathematical reals, not even a tiny little bit. The use of IEEE numbers in serious applications (Bitcoin, iiuc) is truly frightening. They should be considered "useful for computer graphics" (although I can't say whether modern gpus are using IEEE numbers; they're at least useful for software rendering) and nothing more.
for (Object &o : iter)
being essentially equivalent to for (i = begin_iter; i < end_iter; i++)Edit: Removed asterisks for multiplications, as they got interpreted as markup.
split [a, c[ into [a, b[ and [b, c[
vs.
split [a, c] into [a, b] and [b+e, c]
Could you explain this?
It's all about each language's default semantics -- what can and should be left unsaid, and how that expresses the language's model for array access, pointer de/referencing, and loop control.
For array indexing, the most accommodating syntax is to do what Fortran does: allow the programmer to explicitly specify each array index's closed array range. That may be the most user-tolerant and unambiguous model for arrays, but it doesn't work well if you also want the same syntax to dereference pointers, whose indices must start at 0. Thus array indices of pointer-based languages (always?) start at 0. But that annoys the hell out of folks who work extensively with arrays AND real numbers, where half-open 0-based integer index ranges compel clumsy semantics when iterating over their precious arrays. (Folks like me, BTW.)
I'd agree with that for lots of domains. If you're dealing with indices often you're probably working at the wrong level of abstraction. Indices are just error prone in general even if you count from zero.
I agree on the numbering but many people don't. He doesn't mention how nicely it works with the modulo operator, which is I think the most compelling reason. But having L[2] be the third index in an array is horribly counterintuitive and leads to countless mistakes. CS students when they begin do not like it, it is not natural. It is beaten into them by scary red error messages and instructors over months and years until they finally accept it.
For 0 based indexing the punctuation is the indexes/offsets:
[ a , b , c ]
0 1 2 3
for 1 based indexing consider the actual elements are the indexes/positions: [ a , b , c ]
1 2 3
In the first case it is non inclusive, ie. elements[0:3] - all items between offset 0 and 3
The second case is inclusive, ie. elements[1:3] - all items including 1 and 3
Personally I don't have an issue with either, they both 'make sense'Where they stop making sense is when you'd mix up the inclusivity ie (for the second case).
elements[1:4] - including item 1 not including 4 p == &(p[0])
p[0] == *(p+0)
p[1] == *(p+1)
where p is a pointer to some arbitrary data type. Then it becomes an offset in memory.At the same time, it's not actually all that common to index elements in loops these days - most languages have some kind of a for-each construct that hides indices (and some, like Python, only have such a construct).
Really, that's just a confusion caused by language and historical accidents.
There is nothing that inherently links "one" to "first", or "two" to "second"--it just so happens that for some weird reason, it's common in English to abbreviate "first" as "1st", "second" as "2nd", and so on.
But just as "A" is the first letter of the alphabet (and not, say, the Ast), "0" is the first cardinal number, and "first" is the first ordinal number.
And there is a very simple reason why zero is the correct default first array index: Zero is the neutral element of addition, and (sub)array indexing is an additive operation.
Zero indicates the absence of a value in our numbering system. If I have a single apple, I have 1 Apple, not 0 Apples. Thus if I have 1 element in an Array I have element[1], not element[0]. It is more natural for us to use numbers not by their cardinal position in a set, but by their inferred value... because they represent quantities.
I am one of those who feels the confusion around zero bounded indexes leads to countless issues because it is counter-intuitive to how we use numbers in real life. I agree it is beaten into developers that this is how is should be, but to me we would have been further ahead to let developers accept what comes intuitively.
So, you would say that "A" is not the first element of the alphabet or that "0" is not the first cardinal number?
> Zero indicates the absence of a value in our numbering system.
You are utterly confused. If I have an account balance of zero, that indicates an absence of a value? How is zero mathematically any different then +1000 or -1000 that justifies making it a special case?
> If I have a single apple, I have 1 Apple, not 0 Apples. Thus if I have 1 element in an Array I have element[1], not element[0].
You are mixing up ordinal and cardinal numbers.
> It is more natural for us to use numbers not by their cardinal position in a set, but by their inferred value... because they represent quantities.
There is no such thing as a "cardinal position", positions are ordinal, cardinality describes sizes.
> I am one of those who feels the confusion around zero bounded indexes leads to countless issues because it is counter-intuitive to how we use numbers in real life.
Nope, what leads to problems is that people don't understand the difference between cardinal and ordinal numbers. You cannot fix that by changing the first index, all that causes is a shift to different bugs. Including stuff like equating zero with the absence of a value.
What's counter-intuitive to me is that we habitually call the second floor in a building the "first floor"!
The historical "accident" is that we don't start with "zeroth". That's probably what you wanted to say but the reasoning tripped me up.
Uhm, no, just the opposite.
It's a bit awkward, but once explained it is a quick way to tell the two numbering schemes apart.
Consider the physical world. Let's say you've got three fenceposts (of unit width) in a line standing before you, each separated by 0.5 fencepost-widths of space.
It makes sense to say "the first fencepost." That's the post can be found in the (0.0, 1.0) region of the fence.
But "fencepost 0" or "fencepost 1" are both ambiguous to me: neither 0 nor 1 is inside the region the first fencepost occupies, physically. The mapping isn't intuitive. Both of those numbers point to where the fencepost isn't: just past its ends. Depending on your mindset, you might want to refer to the fencepost either to the left or the right in the row of that imaginary separating line: either "the fencepost that was just completed" or "the fencepost that is about to start" in your visual stream. Even worse if you're from a culture that reads right-to-left.
In physical terms, if you wanted to give "the first fencepost" an address... it'd be fencepost 0.5! Likewise, "the second fencepost" would be fencepost 2.0, and "the third fencepost" would be fencepost 3.5. These numbers refer to the centers of each fencepost. You don't have to ask the question of which "direction you head" to find the fencepost from the address: when you're at the address, you "have" a fencepost. You just need to know the origin and axes of the fence and you can "go to" the fencepost.
Now, we could get fencepost addresses of 0.0, 1.0, 2.0, and so on, by following some indexing strategy like "the position of the left edge of the Nth fencepost, measuring only fencepost-widths and not space between fenceposts." This kind of offset-based indexing is "intuitive" when talking about memory addresses, because memory addresses are like an ideal fence: every post is 1.0 units wide, with no space in-between posts. (Also, you can't actually point to the centre of an atomic unit of memory; memory addresses are quantized such that the only place the "handle" of a memory address can be attached to the memory itself is the "left edge"—the beginning—of the memory.) Great for digital logic, but we just don't have anything like that in physical space.
In reality, when we want indexes, we explicitly label things with numbers from a monotonic sequence, and then either write down mappings from the center-of-measured-interval addresses of the physical world (e.g. GPS coordinates) to those labels, or, worse, binary-search our items for one with the right address-label, hoping the labels have stayed monotonically sorted since they were issued.
There are nearly no cases where there is a natural "element zero" that exists at zero in the physical world, to create that associative intuition (perhaps, people crossing a finish line in a race: the winner is certainly "person zero" in the photo.)
Which is good, because it means that you are not confused :-)
The confusion is the idea that there is an inherent link between "1" and "first" or "0" and "first", which there isn't, because one of them is a label, while the other is an ordinal number.
You need a definition of how to map one to the other, and as long as you don't have that, the labels do indeed remain ambiguous, which you correctly recognize.
Now, there is an argument to be made for why array indexing should use a definition that maps the first element to label 0, and that is, as I wrote, that array indexing is an additive operation.
As for how that connects to your fence example: What you necessarily need in addition if you want to model your fence with an array(!) is a definition that maps your fence posts' positions to ordinal numbers, which you then can map to array indices via the definition above. That exact mapping is necessarily arbitrary to a degree, and the only really important thing is that you are consistent.
But within the implementation, you are likely to encounter problems such as "find the third fencepost of the part of the fence that starts at the second fencepost". And that would be the fourth fencepost of the overall fence, not the fifth, or in indices: 1 + 2 = 3 vs. 2 + 3 != 4.
> There are nearly no cases where there is a natural "element zero" that exists at zero in the physical world
Well, nor is there a natural "element one" that exists "at one".
$10 says you don't have any children.
It is practically impossible to teach good programming to
students that have had a prior exposure to BASIC: as
potential programmers they are mentally mutilated beyond
hope of regeneration.
The use of COBOL cripples the mind; its teaching should,
therefore, be regarded as a criminal offence.
APL is a mistake, carried through to perfection. It is the
language of the future for the programming techniques of
the past: it creates a new generation of coding bums.
The use of anthropomorphic terminology when dealing with
computing systems is a symptom of professional immaturity.
More: I think of the company advertising "Thought Processors" or
the college pretending that learning BASIC suffices or at
least helps, whereas the teaching of BASIC should be rated
as a criminal offence: it mutilates the mind beyond
recovery.
Given, I'm cherry-picking here. Not everything Edsger says is like this. Not by a long shot. He is brilliant, make no mistake.But I must leave you with a quote from Sir Alan Kay that I found on the Wikiquote page while I was researching this:
You probably know that arrogance, in computer science, is measured in nanodijkstras.
Given, it's Alan, so I don't know how serious he was being.I think finding fault with this kind of opinion is a symptom of the modern concept of "taking offence". Ie nobody can express an opinion without also showing that they respect others' opinions. But that's not right. We don't have to respect each others' opinions if we think they are wrong. What we must do in a free society is respect their right to have, and express, a different opinion.
Dijkstra clearly thinks that teaching BASIC is damaging people's brains so he says that loudly and clearly with a touch of humour. Should he water it down to avoid offending people that like BASIC?
https://medium.com/@acidflask/this-guys-arrogance-takes-your...
Keep calling it the second, then. And use 'zeroth' for L[0]. Problem solved.
Also, what is 'counterintuitive' is very often just a question of habit. I've many times seen Americans (at least those not scientifically inclined) express confusion over metric units. I have been using the metric system all my life in every its domain: I buy apples in kilograms, measure rooms in metres, water in litres, and I regard it as the most natural thing in the world. I find the American unit system batshit insane (why is 'ounce' a unit of mass, but 'fluid ounce' a unit of volume? WTF is up with all those different conversion factors?) and if I had the power to wipe the it from the face of the Earth, I'd do it in a heartbleed. I'm sure that if I asked some people from my country about this, I'd find many agreeing with me. But I realise there are people who feel just the opposite. (I still think they're wrong, but I get where they're coming from.)
Zero-based indexing is similarly just a question of what people are used to. When those students start appreciating the nicer mathematical properties of zero-based indexing (and half-open ranges that go along with it), it'll become second nature to them. (I suspect the reason why many people don't is because laymen don't often work with abstract algorithms and indexed data structures where those properties display their usefulness.)
L[2] == *(L + 2) == *(2 + L) == 2[L]I started with arrays with Fortran. There can pass an array as an argument to a parameter of a subroutine, and the subroutine can address the darned array any way it wants. Why? Sure, maybe want to sort the array based on a slice here omitting details. Sure, such programming would need a lot of well done documentation and still is dangerous. And such array fooling around stands to get into trouble with compiler options to check array bounds.
Then I did a lot with PL/I: There get arrays, structures, structures of arrays of structures of arrays, etc. Also get to set the lower and upper bounds of each array index to anything -- positive, negative, or zero, including during execution -- that can be represented in the usually 16 bit array indexing arithmetic. And, it turns out, all that array indexing, even for arrays of structures of arrays, etc., is just ordinary multi-dimensional array arithmetic -- nearly as useful as objects but with much simpler storage allocation and array indexing. And if look carefully at that arithmetic, then do see how to have any subscript (index) lower bounds and upper bounds with just trivial modification of the usual array indexing.
And, yes, when I wrote C code, no way did I like the high emphasis on starting an array at index 0. Besides C doesn't even really support arrays, e.g., with several subscripts, and forces a programmer to write a macro or some such that does the arithmetic. And there are problems in a subroutine that receives such an array. And compiler support for checking array bounds is in trouble because the language syntax and semantics don't even support arrays with several dimensions. So, have to write, say, a matrix package that has a C structure for the details of number of dimensions and the upper/lower bounds for each dimension -- it works but get no compiler based debugging support or I/O support, and no doubt the compiler can't do some indexing optimizations that Fortran and PL/I can do because the data being used for the indexing is, in the semantics, not subject to being changed by the user's code during the indexing arithmetic. E.g., with PL/I, in the execution logic, each structure or array, each aggregate has a little table, a dope vector that describes the aggregate, yes, within a subroutine and within runtime subroutines, e.g., for doing I/O on the whole aggregate.
PL/I was in good shape before C was developed. PL/I was used for the operating systems Multics and much of Primos. So, PL/I offers programmers much more than C and, still, is good for both applications and operating system code, especially in array indexing.
Sorry, Dijkstra.
https://learnxinyminutes.com/docs/c/ then text seach for "dimensional".
More detail: http://beginnersbook.com/2014/01/2d-arrays-in-c-example/
I didn't see that in K&R, 1988. Are such multi-dimensional arrays new since 1988?
When I needed to do a little matrix work in C, I just wrote my own little package of matrix code, maybe with more functionality than I just saw in your first link. Maybe I didn't really need to write my own?
Nice of you to speak for them. Unfortunately you are in error.
Frankly, I find Dijkstra's writing horribly grating and irritating. The majority of his articles seem to be just him insulting things he doesn't like, another thing I find grating (for one thing, I can't think of anything he does like off the top of my head). He also seems to have a habit of passing his opinions off as fact.
But he is really smart, and often right, so while I can be annoyed by him, I can't actually ignore what he says, because it does matter.
it's been occasionally opined that the biggest issue Dijkstra had with computer science is that it often needed to be applied to computers.
according to at least one attempt 0 based indexing was chosen because it was slightly faster to compile.
We do, not when they're starting out but the number line is introduced pretty early to children. Even earlier we teach them to count backwards with zero being the final element. Kids aren't strangers to the concept of zero.
I don't know if this is still the case -- my understanding of microprocessor architecture is about 30 years old.
Nowadays I do write stuff but summarize it into the computer. I've tried various tools for automatic capture (e.g. livescribe) but they don't work that well. I realized that the probably would have worked great with my 35-years-ago handwriting.
[1] https://en.wikipedia.org/wiki/OpenType#Advanced_typography [2] https://en.wikipedia.org/wiki/Font#Character_variants
(Charles Rennie Mackintosh has particularly lovely drafting letters; turned into the Hill House font.)
Edit: I can't explain how, but the first time I downloaded that PDF I received a file which looked different. Here is a similar file from the same site which clearly resembles what led me to make the comment above:
https://www.cs.utexas.edu/users/EWD/ewd00xx/EWD77.PDF
So I apologise for this unnecessary diversion from the topic.
http://stackoverflow.com/questions/37953786/why-does-postgre...
It is interesting to see the same question applied to natural numbers, and Dijkstra landing on the same [x, y) recommendation. I'd say for natural numbers the argument is even stronger, since there is a least possible value.
Try some string manipulation using the awk language, which has 1-based strings and arrays, and you'll see that programs and string expressions are generally shorter and more idiomatic.
Later languages building on awk such as Java and JavaScript (awk is almost a subset of, and the inspiration for early JavaScript) have cargo-culted 0 into the language as base offset. Though probably it may have prevented some errors to make commonly used languages behave same in this respect.
Depends very much on what you're doing. If you're doing, say, a filesystem driver, and you need to do math or reasoning on [offset, length] pairs quite frequently, you will find 0-based indexing much more natural. At least that's been my experience. I think some of this applies to strings and memory too.
In the west, we measure our age and start from 0. In China, they count their age (number of distinct years someone has been alive in) and thus start from 1. In fact, in China, if you are born on new years eve you can be 2 years old at 2 days old!
But it doesn't really apply in the natural world, where 1 is a much better starting number for probably all contexts where you have to number or reference things in an order.
Maybe this clarification is redundant, I don't know. But when I read the headline, I assumed it was talking about everywhere, which is why I found it interesting and even clicked it in the first place.
I'd say that the only situation where it makes sense to count from 1 is when you are counting objects. Of course, counting objects is so important that it dominates people's perception of numbers and counting.
"pause one, pause two, ..."
So when you get to 10, you have said 10 numbers and there have been ten pauses. The "you are only counting 9 seconds" thing would only make sense if the counting period starts when you say the first number, which is not how I usually do it...
Anyway, if you do make a conscious pause, I would argue that you are effectively counting from 0 even if you don't pronounce 0 due to the bias against that number caused by counting objects. The first pause needs to start somewhere, the start of that pause is in your mind (even if you don't pronounce it) and it corresponds to 0.
In naive set theory, starting with 1 poses some problems (specifically, you don't have numbers yet, so you start with the notion of the empty set, which you use to define 0, and then proceed from there).
Starting the naturals from 0 is also problematic in group theory, since you lose the additive identity.
for i in 0u8..256 { } // <-- doesn't compile, because 265 is not a valid value for a u8when you see `-1` in code it is often a failure of the expressiveness of 0-indexed lists. For example, the last item in an array:
arr[arr.length - 1]
Or a found item by index number: if (arr.indexOf("thing") > -1) {
This is hardly an elegant convention....And when you see '+1' or '(x%ArrayLen)+1' or 'x<=arrayLen', in lua or FORTRAN it is often a failure in the expressiveness of one-indexed lists.
Also, I don't think the parent's point is "1 is better than 0" but rather "0 is not better than 1".
a[N : length(a) - N + 1]
However, if you do have such special support - e.g. if negative indices are treated as from-the-end (like Python does), then it's just: a[N : -N]
Compare this to 0-based N with end-exclusive slices (again, as is typical). If you don't have reverse indexing, it's slightly simpler: a[N : length(a)]
but with reverse indexing (where -1 is the last element), it's actually worse: a[N : -N - 1]
FWIW, most of it has more to do with the fact that 1) negative numbers are probably not the best way to represent reverse indices, and 2) depending on the situation, either end-inclusive or end-exclusive can be convenient.In fact, merely having a special syntax for reverse indexing solves it for 0-based languages. For example, suppose that we extend the slice syntax such that either index can be prefixed with ~ to indicate indexing from the end. Then ~0 is the last element, and it becomes:
a[N : ~N]
This has a side benefit of avoiding errors when the computed index is accidentally negative, and ends up being treated as reverse, even though that was not actually the intent. Encoding the direction in the slice syntax itself means no runtime magic.Alternatively, you can provide syntactic sugar for the length of the array within the indexer - say, `$`. Then, in 0-based end-exclusive approach, you just write:
a[N : $ - N]
This is one case that 1-based approach doesn't handle nearly as well, because for the same simple syntax to work there, you'd need to make $ be length + 1, which is kinda ugly.However, this only works if your ranges aren't first-class (i.e. if they only appear inside []). These days, the trend seems to be to have ranges as first-class values in the language, and have the indexer accept a range as an operand. In that case, since the range can be constructed separately, it needs to be able to encode "index from start" and "index from end" inside the object itself, and special range syntax for that makes more sense.
If the language uses iterators or equivalent, then the iterator itself can encode the direction, and the range is just a pair of iterators. But you would still want some special short syntax, or at least a short convenience function, to easily create reverse iterators. C++ does just that - a pair of iterators expressing the same thing for random-access container `a` would be:
make_pair(a.begin() + N, a.rbegin() + N)
This is very generic, but the annoyance here is that you have to repeat `a` twice, and it could be a lengthy expression, or even have side effects. Some form of let..in syntax to introduce local bindings in expressions, like ML does, would help a lot here - you could do e.g.: let a = <some very long expression>
in make_pair(a.begin() + N, a.rbegin() + N)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.
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.
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.
Modulo and exponents are, to me, the primary reason for using a 0 based numbering system
C++ has arr.back() which is much nicer to read, but has the downside that behaviour is undefined when the vector is empty. Seems like interfaces always have pain points.
arr.indexOf("thing") > -1
... this one is hardly related to zero-indexing. If indexOf returned 0, this would be equally inelegant. arr[arr.length - 1]
Of course, one could argue that this just means that the length of an array is a less meaningful property than its last populated index (what Perl calls `$#array`); one can imagine arr[arr.lastIndex]
or, which is probably better, just arr.last
> Or a found item by index number: if (arr.indexOf("thing") > -1) {
This comes from overloading return values to communicate errors. It's not clear to me that if (arr.indexOf("thing") > 0) {
(in a hypothetical analogue with 1-indexed lists) demonstrates any clear improvement; something like if (arr.member?("thing")) {
seems preferable in terms of clarity (ignoring the efficiency objection that one would probably immediately after look for the index).This is not commonly held belief. I am in minority but this is what makes sense and I always believed that computers should serve us, not the other way around.
Amen! The idea that we should change our way of thinking because it somehow makes more sense for computers is preposterous.
1. Naturally, the first element in a list cardinally corresponds to 1. Contrarily, even official documentation of JavaScript has explicit disclaimers that the "first element of an array is actually at index 0" - this is easily forgotten, especially by novices, and can lead to errors.
2. Mathematically, a closed interval is properly represented in code as for(i = 1; i <= items.length; i++), because it includes its endpoints. Offset notation instead is technically a left-closed right-open interval set, represented in code as for(i = 0; i < items.length; i++). This matters because code deals with integer intervals, because all elements have a fixed size - you can not access a fractional part of an element. Integer intervals are closed intervals, thus conclusively proving this importance.
3. Mathematically, matrix notation also starts with 1.
4. The last element in a list cardinally corresponds to the length of the list, thus allowing easy access with items.length rather than having frustrating (items.length - 1) arithmetic everywhere in your code.
5. Negative indices are symmetric with positive indices. Such that -1 and 1 respectively refer to the last and first element, and in the case where there is only one item in the list, it matches the same element. This convenience allows for simple left and right access that offset notation does not provide.
6. Non existence of an element can be represented by 0, which would conveniently code elegantly as if( !items.indexOf('z') ) return;. Rather, one must decide upon whether if( items.indexOf('z') == -1 ) return; is philosophically more meaningful than if( items.indexOf('z') < 0 ) return; with offset notation despite ignoring the asymmetry of the equation.
And choosing "0" to mean "absent" is as arbitary and misguided (unless you are optimizing bits and cycles on a low-powered machine) as choosing "-1" to mean "absent"
'Cardinally' is wrong; it refers to cardinality, i.e. measuring the size, not indexing. It's just a historical accident that indexing traditionally started with one, and most languages lack a word for an ordinal number corresponding to zero. That's mostly because for a long time zero hasn't even been recognised as a number at all.
But the Ancient Greeks didn't recognise 1 as a number either. We've grown past that.
> 2. [...] This matters because code deals with integer intervals, because all elements have a fixed size - you can not access a fractional part of an element. Integer intervals are closed intervals, thus conclusively proving this importance.
Half-open intervals preserve the property that [a,b) ∪ [b,c) = [a,c) whether the domain is discrete or not. Half-open intervals generalise well both to empty ranges and infinite ones. In fact, in set theory ordinal numbers can be said to be defined as half-open intervals starting with zero (according to the most popular modern definition): an ordinal is simply the set of all ordinals that precede it.
The 'fractional part of an element' is nonsense.
> 3. Mathematically, matrix notation also starts with 1.
This is just a historical accident as well.
> 4. The last element in a list cardinally corresponds to the length of the list, thus allowing easy access with items.length rather than having frustrating (items.length - 1) arithmetic everywhere in your code.
That is somewhat obtuse, but I don't believe it outweighs other concerns. And again, not 'cardinally'.
> 5. Negative indices are symmetric with positive indices. Such that -1 and 1 respectively refer to the last and first element, and in the case where there is only one item in the list, it matches the same element. This convenience allows for simple left and right access that offset notation does not provide.
Zero-based indexing together with negative indexing lets you effortlessly treat any list as a circular list. Which is related to the reason why people bring up modulo all the time, by the way.
Tangentially, Lua uses this very convention (1-based indexing, closed ranges and negative indexing) in its string functions. It annoys me every time I write something parser-like by hand.
> 6. Non existence of an element can be represented by 0, which would conveniently code elegantly as if( !items.indexOf('z') ) return; Rather, one must decide upon whether if( items.indexOf('z') == -1 ) return; is philosophically more meaningful than if( items.indexOf('z') < 0 ) return; with offset notation despite ignoring the asymmetry of the equation.
The first is obviously more sensible. Failure to find an element might just as well be represented by a null; that the value chosen to represent it is an integer smaller than any valid index is mostly an accident. In a better-designed programming language, a function equivalent to indexOf would have a return type of an option type of a valid index. The language would also have pattern-matching constructs handling it with a syntax just as snappy as a boolean negation is in JavaScript. (Why? For one, because it generalises well to maps of arbitrary type.) This remark proves little apart from pointing out the shortcomings of JavaScript's type system.
Ask ten people to implement binary search with 1-based indexing, for example. Watch the off-by-ones roll in.
In fact, from https://en.m.wikipedia.org/wiki/Zero-based_numbering With zero-based numbering, a range can be expressed as the half-open interval, [0,n), as opposed to the closed interval, [1,n]. Empty ranges, which often occur in algorithms, are tricky to express with a closed interval without resorting to obtuse conventions like [1,0]. Because of this property, zero-based indexing potentially reduces off-by-one and fencepost errors.
Edit: Lol, the Wikipedia article cites Dijkstra's article.
On its own, I think that's a reasonable contention, but it doesn't work when combing intervals: [1, 1) combined with [1, 2) is still [1, 2), but [1, 0] combined with [0, 2] isn't [1, 2].
[0..5] 0,1,2,3,4,5
(0..5) 1,2,3,4
[0..5) 0,1,2,3,4
(0..5] 1,2,3,4,5
This reflects the concept of closed and open intervals in mathematics. It might have been useful when porting FORTRAN programs to Mesa. In FORTRAN, arrays start from 1. Pascal required a range in the declaration. When C started consistently from 0, that was considered radical.For programming, as Dijkstra mentions, a consistent start from zero seemed to be helpful.
Let's call it $[, so a statement like '$[ = 17' causes arrays to start indexing at 17.
http://search.cpan.org/dist/perl-5.17.1/ext/arybase/arybase....
(C.S. way) 0 <= a < N
(Math way) 0 < b <= N
As he says, both ways have the property that "upper bound - lower bound = Number of elements", both can represent an empty set "lower bound = upper bound", and both make partitioning easy "(0 <= a < M)U(M <= a < N)".
However I disagree that including the lower bound way is preferable to the starting at 1, math way. Math is the older science and children are still taught to count in this way.
As many of the benefits of one way or the other are mostly just network effects (i.e. in math subscripts typically start at 1 or in C, ints and structs are pointed to by their lowest char), we should have used the notation of the older science.
What's happening here is experts arguing about minutia that feels important to them, but looks trivial from the outside.
[1-based index] Year 2016 -> Century 21 -> Millennium 3
New year on 2017-01-01 01:01:01
[0-based index] Year 2015 -> Century 20 -> Millennium 2
New year on 2016-00-00 00:00:00 :-)
Why do people make the fuss about indexing and not about column-major arrays?
Such minimalism is elegant and efficient, to be sure, and I'm a big believer that beauty often shows the path to truth. So from a computer science standpoint, I wholly agree.
From a software engineering standpoint it's really fucking stupid. People generally learn to count on their fingers and they need to grasp the concept of counting and numbers as an abstraction before they can get with the concept of a zero.
Counting on your fingers is one of those very basic things like learning the alphabet (ro its equivalent in other languages) or learning to tie shoelaces. Nobody I have ever met defaults to counting from zero, not even people who claim to do so - easily tested by buying them a drink at some later time and tricking them into counting something.
If you're a software engineer your job is to build something that works and is maintainable. This is not the same thing as doing computer science or mathematical computing, even though it may all be math from the computer's point of view - just as architects are not mathematicians despite their reliance on geometry. Array bound errors are omnipresent in software projects because counting everything from zero is directly at odds with how we count things in the real world, and when we're in a hurry or under pressure we default to learned behaviors. Even people who have been bilingual for years will burst into their default language or switch between two default languages when they're excited. Building your code to go from 1 to n+1 may not be quite as beautiful, but it is a hell of a lot easier for other people to read and (in my experience) you make fewer mistakes if you switch away from starting at zero.
Yes, this requires developing some new habits that feel really awkward at first. Since I've only ever programmed for myself rather than as part of a team I haven't had to deal with the inevitable resistance to this. But it is worth making the switch. Just as a lab and a construction site are very different environments [1], so are the practices of computer science and commercial software development. It would also make a huge difference in programming education, where many prospective students are alienated by being asked to do something highly counterintuitive very early on (typically while trying to grasp the concept of looping) and lead to errors which they are likely to keep making forever because nobody defaults to counting from zero in any other context.
If you're a computer scientist, carry on as you were. If you're an engineer, then build for the needs and instincts of your end users - some of whom will eventually be programmers - and not for the computer gods. They're not going to be around to help when your code breaks down.
I'm not very optimistic about this plea (especially not in the USA where y'all won't even adopt the damn metric system), but please at least give it a try. Technology should adapt to the needs of the people that use it, rather than the other way around. If you're working in a high level language, then use high level concepts.
1. Remember the story about the three little pigs who all built their houses out of subatomic particles formed into atoms formed into molecules and whose houses were topologically identical but had different coefficients of structural stability? Me neither.
(And for the record, I started out in the 1-origin Basic and Fortran world; my preference isn't just a matter of which one I learned first.)
Surely not the Noble kind of sciences, but if animosity leads too thoroughly read papers and found errors, maybe the dark side is just willing to work harder.