Ranges to deal with corner cases and "random access"

Paul Backus snarwin at gmail.com
Tue Oct 8 15:40:33 UTC 2019


On Sunday, 6 October 2019 at 20:34:55 UTC, Brett wrote:
> If it can be done and make to work well with ranges it would 
> allow many algorithms to be very easily expressed and make 
> ranges more powerful.

You can make it a range by adding an "alias this" to the original 
array:

struct ExtendedArray(T)
{
     T[] a;
     alias a this;

     T opIndex(int i)
     {
         if (i < 0) return a[0];
         else if (i >= a.length) return a[$-1];
         else return a[i];
     }
}

Full example: https://run.dlang.io/is/2x6LKD


More information about the Digitalmars-d-learn mailing list