Multidimensional slice
Remi Thebault via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat Aug 9 13:43:32 PDT 2014
Hello D-community
Sorry to dig an old post, but I have the exact same need.
I have C++ background and I started to use D a few days ago only
(a pity I didn't start sooner!)
My needs are mostly around numerical calculations. I have a safe
and efficient matrix type in C++ that I am porting to D.
Implementation is really easier, no doubt.
I have coded slicing following this page
http://dlang.org/operatoroverloading.html#Slice
but the code doesn't compile.
here is a reduced and simplified code:
struct slice
{
uint start;
uint size;
}
struct Example
{
int[] array;
uint rows;
uint cols;
uint start;
uint stride;
this(int[] array, uint rows, uint cols, uint start=0, uint
stride=uint.max)
{
this.array = array;
this.rows = rows;
this.cols = cols;
this.start = start;
this.stride = stride == uint.max ? cols : stride;
}
uint opDollar(uint dim)()
{
static assert(dim <= 1);
static if (dim == 0) return rows;
else return cols;
}
slice opSlice(uint from, uint to)
{
return slice(from, to-from);
}
int opIndex(uint r, uint c) {
return array[start + r*stride + c];
}
// int[] opIndex(slice rs, uint c) {
// // ...
// }
// int[] opIndex(uint r, slice cs) {
// // ...
// }
Example opIndex(slice rs, slice cs)
{
uint r = rs.size;
uint c = cs.size;
uint s = start + rs.start*stride + cs.start;
return Example(array, r, c, s, stride);
}
}
int main() {
auto m = Example([ 11, 12, 13, 14,
21, 22, 23, 24,
31, 32, 33, 34,
41, 42, 43, 44,
51, 52, 53, 54 ],
5, 4);
assert (m[3, 2] == 43);
auto m2 = m[slice(2, 3), slice(2, 2)]; // <- this is the
construct I use in C++
assert (m2[1, 0] == 43);
assert (m2.rows == 3 && m2.cols == 2);
// m3 should refer to the same slice as m2
auto m3 = m[2..5, 2..4]; // <- compiler syntax error is
here
assert (m3[1, 0] == 43);
assert (m3.rows == 3 && m3.cols == 2);
return 0;
}
the compiler kicks me out with a syntax error:
Error: found ',' when expecting ']'
Error: semicolon expected following auto declaration, not '2'
Error: found '..' when expecting ';' following statement
Error: found ']' when expecting ';' following statement
Have I done something wrong?
Or may be has the documentation been quicker than the compiler
implementation?
Or a compiler bug?
thanks
Rémi
More information about the Digitalmars-d-learn
mailing list