is this considered inconsistency?

mw mingwu at gmail.com
Sun Mar 21 16:27:06 UTC 2021


On Sunday, 21 March 2021 at 16:21:44 UTC, Steven Schveighoffer 
wrote:
> On 3/21/21 11:55 AM, mw wrote:
>> https://run.dlang.io/is/VOGlGN
>> 
>> void main()
>> {
>>      import std.stdio: writeln;
>>      {
>>          // example from "Introduction to Algorithms" Cormen 
>> et al., p 146
>>          int[] a = [ 4, 1, 3, 2, 16, 9, 10, 14, 8, 7 ];
>> 
>>          foreach (i;   0 ..  1 ) writeln(i);  // 0
>>          foreach (i;   0 ..  0 ) writeln(i);  // no output
>>          foreach (i;   0 .. -1 ) writeln(i);  // no output
>> 
>>          foreach (i; a[0 ..  1]) writeln(i);  // 4
>>          foreach (i; a[0 ..  0]) writeln(i);  // no output
>>          foreach (i; a[0 .. -1]) writeln(i);  // Range 
>> violation
>>      }
>> }
>> 
>> Why can't the a[0 .. -1] just return empty range, when end <= 
>> start, as in a[0 ..  0]? and also in foreach (i;   0 .. -1 )?
>> 
>> 
>
> That would be the least useful behavior.

It's useful (to be consistent): it reduces user's burden to write 
the bound check explicitly (verbosely), i.e foreach (i; a[0 .. 
max(0, end)]) {...}




More information about the Digitalmars-d mailing list