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

IGotD- nise at nise.com
Fri Sep 18 20:08:36 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:
>
> 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?

Array indexes in D are using unsigned integers so negative 
numbers don't exist. What you are suggesting isn't possible in D. 
$ is the length of the array so $-1 is correct in this regard and 
produces a correct positive number given that it is inside the 
array bounds.




More information about the Digitalmars-d mailing list