3 ms·
Zero-based counting works better with modular arithmetic. Like arr[(i++ % arr.length)] = foo; Is certainly nicer than the equivalent in one-based subscripti
by sham1 2y ago
Zero-based counting works better with modular arithmetic. Like
arr[(i++ % arr.length)] = foo;
Is certainly nicer than the equivalent in one-based subscripting
arr[(i++ % arr.length) + 1] = foo;
(The above is actually wrong, which helps the idea)
I'll concede that it's not all that significant as a difference, but at least IMO it's nicer.
Also could argue that modular arithmetic and zero-based indexing makes more sense for negative indexing.
- Quekid5 2y agoYes, negative indexing as in e.g. Python (so basically "from the end") can be incredibly convenient and works seamlessly when indexes are 0-based.
- pansa2 2y agoNot quite seamlessly, unfortunately. `l[:n]` gives you the first `n` elements of the list `l`. Ideally `l[-n:]` would give you the last `n` elements - but that doesn't work when `n` is zero. I believe this is why C# introduced a special "index from end" operator, `^`, so you can refer to the end of the array as `^0`.
- UncleEntity 2y agoSo you're saying a negative index value should work like a count of elements to return and not an index? Then you couldn't do thing like l[-4:-2] to get a range of elements which seems slightly useful.
- pansa2 2y agoNo - negative indexing is fine as it is. You just need to be careful about the special case of negative zero.
- Ukv 2y ago> Yes, negative indexing as in e.g. Python (so basically "from the end") can be incredibly convenient and works seamlessly when indexes are 0-based. I'd claim 0-based indexing actually throws an annoying wrench in that. Consider for instance: for n in [3, 2, 1, 0]: start_window = arr[n: n+5] end_window = arr[-n-5: -n] The start_window indexing works fine, but end_window fails when n=0 because -0 is just 0, the start of the array, instead of the end. We're effectively missing one "fence-post". It'd work perfectly fine with MatLab-style (1-based, inclusive ranges) indexing.
- tmtvl 2y agoBut on the other hand, last := vector[vector-length(vector)]; is nicer than last := vector[vector-length(vector) - 1]; so in the end I'd say 'de gustibus non est disputandum' and people who prefer 0-based indexing can use most languages and I can dream of my own.
- naasking 2y agoThat's arguably one of the only downsides of zero-based, and can be handled easily with negative indexing. Basically all indexing arithmetic is easier with zero-based.
- tmtvl 2y agoUsing an array as a heap is also easier with 1-based indexing: base-element := some-vector[i]; left-child := some-vector[i * 2]; right-child := some-vector[i * 2 + 1]; where the root element is `some-vector[1]'.