Iterators in structs

2020-06-25 Thread repr-man via Digitalmars-d-learn
As an extension of my previous thread 
(https://forum.dlang.org/thread/nupwljahyutnyxdvp...@forum.dlang.org), I wanted to ask about iterators in structs.  I will start with the following code:


void main()
{
int[5] a = [0, 1, 2, 3, 4];
int[5] b = [5, 6, 7, 8, 9];

auto x = ChunksOf(chain(a[], b[]), 2);
}

struct ChunksOf
{
this(R)(R r, size_t width)
{
auto iter = r.chunks(width);
assert(is(typeof(iter) == Chunks!R));
}
}

This code works as expected.  However, if the struct changes to:

struct ChunksOf
{
Chunks!R iter;

this(R)(R r, size_t width)
{
this.iter = r.chunks(width);
assert(is(typeof(iter) == Chunks!R));
}
}

it doesn't compile because R is only in the scope of the 
constructor.  This leads me to change the struct to:


struct ChunksOf(R)
{
Chunks!R iter;

this(R r, size_t width)
{
this.iter = r.chunks(width);
assert(is(typeof(iter) == Chunks!R));
}
}

This works, only if I change the declaration of x in main() to:

auto x = ChunksOf!(chain(a[], b[]))(chain(a[], b[]), 2);

This requires me to pass the iterator as a template parameter and 
a regular parameter.  Since this is a bit redundant, and I wanted 
to know if there was a better way to do it.


Thanks for the help!


Passing iterators into functions

2020-06-24 Thread repr-man via Digitalmars-d-learn

I have the code:

int[5] a = [0, 1, 2, 3, 4];
int[5] b = [5, 6, 7, 8, 9];
auto x = chain(a[], b[]).chunks(5);
writeln(x);

It produces a range of slices as is expected: [[0, 1, 2, 3, 4], 
[5, 6, 7, 8, 9]]


However, when I define a function as follows and pass in the 
result of the chain iterator:


auto func(R)(R r, size_t width)
if(isRandomAccessRange!R)
{
return r.chunks(width);
}

void main()
{
int[5] a = [0, 1, 2, 3, 4];
int[5] b = [5, 6, 7, 8, 9];
auto x = func!(int[])(chain(a[], b[]), 5);
writeln(x);
}

It gives me an error along the lines of:
Error: func!(int[]).func(int[] r, ulong width) is not callable 
using argument types (Result, int)
   cannot pass argument chain(a[], b[]) of type Result to 
parameter int[] r


I was hoping it would return the same result as the first program.

This seems to have to do with the fact that all iterators return 
their own unique type.  Could someone help me understand the 
reason behind this design and how to remedy my situation?


Passing a variable number of slices into a function

2020-06-21 Thread repr-man via Digitalmars-d-learn
Is there any way to pass an unknown number of slices into a 
function?  I'm trying to do something along the lines of:


void func(T)(T[] args...)
{
//...
}

That wasn't working, so I tried using another generic type where 
T was already defined:


void func(U)(U args...)
if(is(U == T[])
{
//...
}

This didn't work either, so I wanted to know if I was going in 
the right direction or if I was missing something obvious.


Thanks for the help!