how do I implement opSlice for retro range?

Christian Köstlin christian.koestlin at gmail.com
Fri May 14 10:00:44 UTC 2021


On 2021-05-14 05:49, Jack wrote:
> How can I implement ranges in the retro range? I'd like to do this 
> without allocate a new array with .array from std.array, can I do that?
> 
> use like this:
> 
> ```d
>      auto arr = [1, 2, 3, 4, 5];
>      auto a = new A!int(arr);
>      auto b = a.retro[0 .. 2]; // 4, 5
> ```
> 
> the class:
> 
> ```d
> 
> class A(T)
> {
>      private T[] arr;
> 
>      this(T[] a)
>      {
>          arr = a;
>      }
> 
>      auto opIndex() nothrow
>      {
>          return Range(arr);
>      }
> 
>      auto retro() { return RangeRetro(arr); }
> 
>      protected static struct Range
>      {
>          T[] a;
>          T front() { return a[0]; }
>          T back() { return a[$ - 1]; }
>          void popFront() { a = a[1 .. $]; }
>          bool empty() { return a.length == 0; }
>      }
> 
>      protected static struct RangeRetro
>      {
>          import std.range : popFront;
>          import std.range : popBack;
> 
>          T[] a;
>          T front() { return a[$ - 1]; }
>          T back() { return a[0]; }
>          void popBack() {  a.popFront(); }
>          void popFront() { a.popBack(); }
>          bool empty() { return a.length == 0; }
> 
>          auto opSlice(size_t start, size_t end)
>          {
>             ???
>          }
>      }
> }
> ```
> 
> 
arr.retro()[0..2] already works.

see https://run.dlang.io/is/U8u3br



More information about the Digitalmars-d-learn mailing list