primitive vector types (permutation syntax)

Daniel Keep daniel.keep.lists at gmail.com
Sun Feb 22 17:52:06 PST 2009



bearophile wrote:
> Mattias Holm:
>> I think that the following would work reasonably well:
>> 	allow the [] operator for arrays to take comma separated lists of indices.
>> So the OpenCL like statement:
>> 	v.xyzw = v2.wzyx;
>> will be written as:
>> 	v[0,1,2,3] = v2[3,2,1,0];
> 
> Be careful, I think a syntax like:
> v[0, 1]
> v[0, 1, 2, 3]
> Is better left to index in 2D and 4D arrays.
> nD arrays can be quite important in a language like D.
> 
> So the following may be better and more compatible with the future:
> v[0; 1; 2; 3] = v2[3; 2; 1; 0];
> Or:
> v[(0,1,2,3)] = v2[(3,2,1,0)];
> Or:
> v[[0,1,2,3]] = v2[[3,2,1,0]];
> 
> Bye,
> bearophile

Swizzling a vector and multidimensional access are orthogonal on account
of vectors having only one dimension [1].

struct FloatTuple(size_t n); // exercise to the reader :P

struct vec4f
{
    union
    {
        float[4] data;
        struct { float w, x, y, z; }
    }

    float opIndex(size_t i) { return data[i]; }
    float opIndexAssign(float v, size_t i) { return data[i] = v; }

    FloatTuple!(2) opIndex(size_t i, size_t j)
    {
        return FloatTuple!(2)(data[i],data[j]);
    }

    FloatTuple!(2) opIndexAssign(FloatTuple!(2) vs, size_t i, size_t j)
    {
        data[i] = vs.data[0];
        data[j] = vs.data[1];
        return vs;
    }

    // and so on for 3 and 4 argument versions.
}

Personally, I think something like this is a better idea:

struct vec4f
{
    ...

    FloatTuple!(PermSpec.length) perm(string PermSpec)()
    {
        FloatTuple!(PermSpec.length) vs;
        foreach( i ; Range!(PermSpec.length) )
            vs.data[i] = mixin(`this.`~PermSpec[i]);
        return vs;
    }
}

void main()
{
    vec4f a, b;
    a = ...;
    b = a.perm!("xyzw");
}

  -- Daniel


[1] By this I mean they're a 1D data type; vec4f represents a 4D vector
but in terms of implementation, it has only one dimension: the index of
data.



More information about the Digitalmars-d mailing list