why $ is need to access array [negative index]?

Steven Schveighoffer schveiguy at gmail.com
Fri Sep 18 20:06:01 UTC 2020


On 9/18/20 3:53 PM, 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 would say no. The indexing code lowers to a machine instruction. 
Making it so a negative value means something else means every single 
indexing operation is going to have to check whether it's negative, and 
if so do something completely different.

You can create your own array type if you want this behavior.

-Steve


More information about the Digitalmars-d mailing list