easier way?

Jason Spencer spencer8 at sbcglobal.net
Wed Aug 25 16:11:52 PDT 2010


I have the following sample program:

---
import std.algorithm, std.stdio;

real mean(T: Elem[], Elem)(T data) {
   return reduce!("a + b")(0.0, data) / data.length;
}

real mean(T: Elem[][], Elem)(T data) {
   real partSum = 0;
   int count = 0;
   foreach (row; data)
   {
      partSum += reduce!("a + b")(0.0, row);
      count += row.length;
   }
   return partSum / cast(real) count;
}

void main() {
   real[] r1s = [1.8, 2.0, 2.2];
   real[][] r2s = [[1.8, 1.8, 1.8], [2.0, 2.0, 2.0], [2.2, 2.2,
2.2]];
   auto avg1 = mean(r1s);
   auto avg2a = mean!(real[][], real)(r2s);
   auto avg2b = mean(r2s);

   writefln("avg1 = %5.3f, avg2 = %5.3f", avg1, avg2a);
}
---

Compiling gives me:
C:\>bud mean.d
mean.d(23): Error: template mean.mean(T : Elem[],Elem) mean(T :
Elem[],Elem) matches more than one template declaration,
mean.d(3):mean(T : Elem[],Elem) and mean.d(7):mean(T :
Elem[][],Elem)

which is the line declaring avg2b.  I'd much rather not have to
specify the full template arguments and instead have the compiler
figure it out, but I also need the Elem type templated and I need
both 1-D and 2-D (and even 3-D) versions.  Is there a better way to
lay this out?

In general, I'm having a hard time with rectangular arrays.
Although they seem like a huge step up from C arrays, in practice, I
find myself back in pointer land more often than not.  For instance,
I can't/don't know how to:
 - get the count of elements in a n-D array w/o iterating over n-1
dimensions
 - get the size easily without pointer tricks that are still
strictly speaking not safe without iterating over n-1 dimensions
 - (as above) discriminate on array types passed 1-D, esp. at
compile time.  i.e. I can't make any template functions to work on
arrays of varying dimensions unless they're static arrays, which
doesn't really help.

Am I pretty normal, or am I missing a good tutorial somewhere?

Thanks,
Jason


More information about the Digitalmars-d-learn mailing list