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

mipri mipri at minimaltype.com
Fri Sep 18 20:58:02 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.

The hardship isn't typing a single character, but requiring an
explicit test to determine whether you should index with or
without that single character.

Consider:

   int ex(int i) {
       immutable int[3] ns = [1, 2, 3];
       if (i < 0) {
           return ns[$+i];
       } else {
           return ns[i];
       }
   }

   void main() {
       import std.stdio, std.range, std.algorithm;
       iota(3)
           .map!(n => n - 1)
           .map!ex
           .each!writeln;
   }

In Python you can calculate an index on a numeric plane that
includes negative numbers and then use it; in D you have some
syntax to conveniently refer to the size of the array.


More information about the Digitalmars-d mailing list