How to use ranges?

anonymous via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Aug 23 06:46:28 PDT 2015


On Sunday 23 August 2015 12:17, Doolan wrote:

> And the use of auto everywhere makes it really hard to tell what
> types I should be using for anything. My compiler talks about
> RangeT!(whatever) but you try to use RangeT!(whatever) and you
> find out RangeT is private...

You can use typeof to get the type of a range expression when typing it out 
is impractical/impossible.

> Can someone give me a short summary of how to use ranges?

I'm not sure what exactly you're looking for. The documentation for tee has 
some example code. How about you show something you're having trouble with?

> And how do they relate to slices? That line is really blurry...

"Slice" is a synonym for what the spec calls a "dynamic array", i.e. a 
structure containing a pointer and a length.

"Slicing" a dynamic array, static array, or pointer produces a dynamic 
array, referencing (not copying) the sliced elements:

----
int[] d = [1, 2, 3, 4]; /* dynamic array */
int[] slice = d[1 .. 3];
assert(slice == [2, 3]);

d[1] = 20;
assert(slice[0] == 20);

int[4] s = [1, 2, 3, 4]; /* static array */
slice = s[];
assert(slice == [1, 2, 3, 4]);

int* p = [1, 2, 3, 4].ptr; /* pointer */
slice = p[1 .. 3];
assert(slice == [2, 3]);
----

Note that the source types are different, but slicing them yields the same 
type every time: int[].

Generally, dynamic arrays / slices are random-access ranges. Narrow strings 
(string/wstring/char[]/wchar[]/...) are a notable exception to this. They 
are dynamic arrays of UTF-8/UTF-16 code units. But they're not random-access 
ranges of Unicode code units. Instead, they're _forward_ ranges of Unicode 
code _points_ (dchar). They have special range primitives that to the 
decoding.



More information about the Digitalmars-d-learn mailing list