why $ is need to access array [negative index]?
no at spam.net
Fri Sep 18 20:48:47 UTC 2020
On Friday, 18 September 2020 at 19:53:41 UTC, mw wrote:
> In Python it's such a convenience to be able to access array
> element from the end:
> in D, we can do that too, but need an extra $: arr[$-1]
> I'm porting some code from Python to D:
> int signs; // sign: -1, 0, 1
> int sign = -1; // for example
> writeln(signs[sign]); // Range violation
> // Error: array index 18446744073709551615 is out of bounds
> signs[0 .. 3]
> (yes, I know I can use AA, int[int], but it just make things
> Can we have a DIP remove / make optional `$` in this usage?
I'm inclined to say typing a single character is not a hardship
in exchange for extreme clarity of the code. Keep in mind that
Python is not the only language with a negative array index.
For instance, C supports it:
That's probably the place to look if you want to start, given the
relationship of C and D.
Then there's R, for which x[-1] means to drop the first element.
That makes a lot of sense if x is treated as a vector of data.
Python's usage, on the other hand, is not at all intuitive. Why
-4 would mean the fourth to last element is unclear. I believe it
was copied from Perl. Ruby does the same thing.
Then there's PHP, which allows you to use a negative array index
as an arbitrary reference to an element: x[-2] could be any of
are actually properties or something like that.
Bottom line is that the Python approach is one of many, it only
makes sense if someone tells you what it means, and it saves you
a single character in return for less clear code.
As noted, it's really easy to create a struct that operates like
Python if you want. That's the beauty of D.
More information about the Digitalmars-d