Ranges to deal with corner cases and "random access"

Jonathan M Davis newsgroup.d at jmdavisprog.com
Tue Oct 8 16:25:19 UTC 2019


On Tuesday, October 8, 2019 9:40:33 AM MDT Paul Backus via Digitalmars-d-
learn wrote:
> 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

It would be less error-prone to just implement the appropriate functions on
the struct. alias this and generic code are a terrible combination. It's way
too easy for a type to pass a template constraint thanks to alias this and
then have trouble because it passed based on the implicit conversion, but
the conversion wasn't forced in the code using the type. You can get some
really subtle problems if the code converts to the alias in some cases but
not in others.

- Jonathan M Davis





More information about the Digitalmars-d-learn mailing list