logoalt Hacker News

Fraterkesyesterday at 12:16 PM3 repliesview on HN

No indexing system is perfect, but one can be better than another. Being able to do array[array.length()] to get the last item is more concise and less error prone than having to add -1 every time.

Programming languages are filled with tiny design choices that don’t completely prevent mistakes (that would be impossible) but do make them less likely.


Replies

adrian_byesterday at 1:36 PM

Having to use something like array[length] to get the last element demonstrates a defect of that programming language.

There are better programming languages, where you do not need to do what you say.

Some languages, like Ada, have special array attributes for accessing the first and the last elements.

Other languages, like Icon, allow the use of both non-negative indices and of negative indices, where non-negative indices access the array from its first element towards its last element, while negative indices access the array from its last element towards its first element.

I consider that your solution, i.e. using array[length] instead of array[length-1], is much worse. While it scores a point for simplifying this particular expression, it loses points by making other expressions more complex.

There are a lot of better programming languages than the few that due to historical accidents happen to be popular today.

It is sad that the designers of most of the languages that attempt today to replace C and C++ have not done due diligence by studying the history of programming languages before designing a new programming language. Had they done that, they could have avoided repeating the same mistakes of the languages with which they want to compete.

tialaramexyesterday at 5:18 PM

array[array.length()] is nonsense if the array is empty.

You should prefer a language, like Rust, in which [T]::last is Option<&T> -- that is, we can ask for a reference to the last item, but there might not be one and so we're encouraged to do something about that.

IMNSHO The pit of success you're looking for is best dug with such features and not via fiddling with the index scheme.

GoblinSlayeryesterday at 2:46 PM

If your design works better in one scenario usually means it works worse in other scenarios, you just shuffled garbage around.