Disjoint slices of an array as reference

Ali Çehreli acehreli at yahoo.com
Thu Aug 20 08:26:59 UTC 2020


On 8/19/20 9:11 PM, data pulverizer wrote:
> On Thursday, 20 August 2020 at 03:47:15 UTC, Paul Backus wrote:
>> double[][] y;
>> y ~= x[0..5];
> 
> Thanks. I might go for a design like this:
> 
> ```
> struct View(T){
>    T* data;
>    long[2][] ranges;
> }
> ```
> The ranges are were the slices are stored and T* (maybe even 
> immutable(T*)) is a pointer is to the start of the original array. I'll 
> use an opIndex that calculates the correct index in the original array 
> to obtain the right data.
> 

I implemented the same idea recently; it's a fun exercise. :) I didn't 
bother with opIndex because my use case was happy with just the 
InputRange primitives (and .length I think).

And I had to implement it because std.range.chain works only with 
statically known number of sub-ranges. :/ If the number of ranges are 
known, then this works:

import std.stdio;
import std.range;

void main() {
   auto x = [1,  2,  3, 4,  5,
             6,  7,  8, 9,  10,
             11, 12, 13, 14, 15];
   auto y = chain(x[0..5], x[9..14]);
   writeln(y);
}

[1, 2, 3, 4, 5, 10, 11, 12, 13, 14]

Ali



More information about the Digitalmars-d-learn mailing list