why $ is need to access array [negative index]?
bachmeier
no at spam.net
Fri Sep 18 20:57:04 UTC 2020
On Friday, 18 September 2020 at 20:48:47 UTC, bachmeier wrote:
> 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:
>>
>> arr[-1]
>>
>> in D, we can do that too, but need an extra $: arr[$-1]
>>
>> I'm porting some code from Python to D:
>>
>> int[3] 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
>> complicated)
>>
>> Can we have a DIP remove / make optional `$` in this usage?
>>
>> Thoughts?
>
> 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:
>
> https://stackoverflow.com/questions/3473675/are-negative-array-indexes-allowed-in-c
>
> 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 the elements.
>
> The strange one is Javascript, which has negative indexes that
> 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.
I forgot to add when discussing C, that D already has negative
index values, which mean something completely different than
Python's usage:
double[] x = [1, 2, 3, 4];
double * y = &(x.ptr)[2];
writeln(y[-2]); // 1
More information about the Digitalmars-d
mailing list