3d vector struct
Craig Dillabaugh
cdillaba at cg.scs.carleton.ca
Mon Feb 3 12:39:37 PST 2014
> 5) I notice that a lot of other people online prefer using
> fixed arrays not structs for Vectors in D, why?
It does make some calculations more straightforward. For example
I have code that calculates distance between points as follows:
double euclideanDistance( double[] pt1, double[] pt2 ) in {
assert( pt1.length == pt2.length );
} body {
return sqrt(
0.0.reduce!( (sum,pair) => sum +
(pair[0]-pair[1])^^2)(zip(pt1, pt2))
);
}
Now a point is not a vector, but they are similar in many
respects. That fact that I use an array for my points makes such
calculations possible. Furthermore you can always add methods to
your struct that let users access the appropriate indices as x, y
and z. If you use UFCS (I haven't yet) you could make these
appear to user code just as if you had named your variables x, y,
and z.
Finally, maybe as some point you want to support vectors of
varied dimension ... it then becomes easier to port your struct.
> 6) Any other comments or suggestions?
Once you have your design more or less settled you should make it
generic (if not for practical reasons just for fun and
experience). You likely want your type to support only
floating-point values, so you can see here how types can be
restricted to FP (see line 50).
https://github.com/craig-dillabaugh/phobos/blob/master/std/complex.d
Thats my fork of the Phobos libraries, likely a bit out of date,
but I was too lazy to look up the prope URL.
More information about the Digitalmars-d-learn
mailing list