easier way?

bearophile bearophileHUGS at lycos.com
Wed Aug 25 17:13:56 PDT 2010


Jason Spencer:

> Is there a better way to lay this out?

Is this good enough for you?

import std.stdio: writefln;
import std.algorithm: reduce;
import std.traits: isArray;

real mean(T)(T[] array) if (!isArray!T) {
    return reduce!q{a + b}(0.0, array) / array.length;
}

real mean(T)(T[][] mat) if (!isArray!T) {
    real partSum = 0.0;
    int count = 0;
    foreach (row; mat) {
        partSum += reduce!q{a + b}(0.0, row);
        count += row.length;
    }
    return partSum / count;
}

void main() {
    real[] r1s = [1.8, 2.0, 2.2];
    auto avg1 = mean(r1s);
    writefln("avg1 = %5.3f", avg1);

    real[][] r2s = [[1.8, 1.8, 1.8], [2.0, 2.0, 2.0], [2.2, 2.2, 2.2]];
    auto avg2 = mean(r2s);
    writefln("avg2 = %5.3f", avg2);
}



> In general, I'm having a hard time with rectangular arrays.

In D there are no built-in rectangular arrays. There are fixed-sized arrays, that when have more than one coordinate are stored in a single contiguous zone of memory, and there are dynamic arrays, that may contain other dynamic arrays, but in general in such array of array rows may differ in length (your code here takes that into account).


> Although they seem like a huge step up from C arrays, in practice, I
> find myself back in pointer land more often than not.

This is not good in D.


>  - get the count of elements in a n-D array w/o iterating over n-1
> dimensions

You can't, because there are no rectangular arrays in D. If you want to be sure they are rectangular you need to build your own matrix struct, that if you want contains a "alias this" :-(


>  - get the size easily without pointer tricks that are still
> strictly speaking not safe without iterating over n-1 dimensions

I don't see how they help here. What kind of pointer tricks?


>  - (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.

My example may help.

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list