easier way?

Philippe Sigaud philippe.sigaud at gmail.com
Thu Aug 26 12:49:56 PDT 2010


On Thu, Aug 26, 2010 at 03:50, bearophile <bearophileHUGS at lycos.com> wrote:

> Jason Spencer:
> > Knowing just the # of dimensions won't tell me
> > the total size or how to index.  I need the size of each dimension.
>
> If you create such structs, you do what you want, so it represents a nD
> rectangular array. The total size is computed by the product of n runtime
> values stored inside the struct itself. And the indexing is not a problem,
> but you need n-1 run-time multiplications to find your index, unless you
> impose the constraint your sizes are a power of two, so you can replace the
> multiplications with shifts, that sometimes may give a small performance
> gain.
>

What bearophile means is something like this:

struct Tensor(T, size_t nDim)
{
     T[nDim] dimensions;
     T[] values;

    this(...) etc.
}

so Tensor!(int,3) is a 3D perfectly cubic 'matrix' if ints, with for example
dimensions 3*5*8.
The only thing CT-defined is the rank (scalar: 0, vector: 1, etc), the
number of dimensions. The dimensions themselves are RT values. The total
size is the product of these values. It can be calculated during
construction.

What you lose is the CT checking that can be done for multiplication or
additions if all dimensions are exposed in the type.
I don't know, would that be an possible addition to Phobos? I remember many
people here creating matrix libraries, so someone probably made this
already.


Concerning arrays of arrays of arrays (or ranges), a useful template is one
that gives the number of []'s, the rank:

template rank(T)
{
  static if (!isArray!T)  // or (isInputRange!T)
    enum size_t rank = 0;
  else
    enum size_t rank = 1 + rank!(ElementType!T); // continue recursion
}

As you can see, it considers a simple scalar type to have rank 0. Maybe
that's not what you want.
This allows you to put simple template constraints, like  if(rank!T == 2)
...

I played with ranges of ranges a few month ago. Maybe some functions there
could interest you:

http://svn.dsource.org/projects/dranges/trunk/dranges/docs/rangeofranges.html
http://www.dsource.org/projects/dranges/browser/trunk/dranges/rangeofranges.d

Mapping a range of ranges, creating them by tensorial product, etc. But the
docs are still incomplete, and the global module is due a clean-up, I'm
afraid.


Philippe
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20100826/b5998c55/attachment.html>


More information about the Digitalmars-d-learn mailing list