Suggestions

Oskar Linde oskar.lindeREM at OVEgmail.com
Mon Dec 4 01:46:01 PST 2006


vincent catrino wrote:
> Hi there,
> 
> I have been following D for about 1.5 year and I really like this
> language. I use it for casual programming and for fun. I'm a
> software engineer using mainly C, JAVA and FORTRAN 77.
> 
> There are a few things that I use all the time in C and JAVA and
> that I really would appreciate to find in the D language.
> 
> * C99 allows the following :
> int func( int n, int a[n][n] ) {
>    ... do something ...
> }
> D forbids this. It is possible to have this in D for example by
> creating a structure like this.
> struct Mati {
>    int *ptr;
>    int dim;
>    int *opIndex(int i) { return ptr + i*dim; }
> };
> and rewriting func like this
> int func( int n, int *ptr ) {
>    Mati m = new Mati();
>    m.ptr = ptr;
>    m.dim = n;
> 
>    m[1][5] = 3;
> }
> Would it be possible to have this in D directly ? Or maybe there
> is a cute D way to have this already and I woould be glad to learn
> it.

D doesn't have dynamic multidimensional arrays built in (it may be on a 
TODO for >= 2.0). A better way is to consistently use a custom array 
type (just like you do). I.e. something like:

struct SquareMatrix {
   int *ptr;
   int dim;
   int opIndex(int i, int j) { return ptr[j+i*dim]; }
   int opIndexAssign(int v, int i, int j) { return ptr[j+i*dim] = v;}
}

(Or the Mati one above) And pass that directly to the functions:

int func(SquareMatrix m) {
	m[1,5] = 3;
	...
}

I have written several such array and matrix types and they work well in 
practice. The downsides are:

- No reference return type from opIndex, meaning e.g, m[1,5]++; is 
impossible. (You solve that quite neatly)
- Not standardized
- Mixing slicing and indexing not possible with the .. syntax

Regards,

Oskar



More information about the Digitalmars-d mailing list