Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a constant record containing other constant records in Delphi? Specific case: matrix using vectors

Say I have a simple record in a unit, such as:

TVector2D = record
public
  class function New(const x, y: Accuracy): TVector2D; static;
public
  x, y: Accuracy;
end;

I then have a second record in the same unit that is built using a set of the above records, such as:

TMatrix3D = record
public
  class function New(const row1, row2, row3: TVector3D): TMatrix3D; static;
public
  Index : array [0..2] of TVector3D;
end;

I then define axis direction constants as follows:

//Unit vector constants
const
  iHat : TVector3D = (x: 1; y: 0; z: 0);
  jHat : TVector3D = (x: 0; y: 1; z: 0);
  kHat : TVector3D = (x: 0; y: 0; z: 1);

I want now to define a further constant using the above constants, something like:

  identity : TMatrix3D = (row1: iHat; row2: jHat; row3: kHat);

Yet the above attempt doesn't work. How would I do this in Delphi XE2?

Many thanks in advance for your efforts. :-)

like image 858
Trojanian Avatar asked Feb 24 '15 15:02

Trojanian


People also ask

How do you declare constants in Delphi?

To declare a record constant, specify the value of each field - as fieldName: value , with the field assignments separated by semicolons - in parentheses at the end of the declaration. The values must be represented by constant expressions.

How do you assign a constant?

You use the Const statement to declare a constant and set its value. By declaring a constant, you assign a meaningful name to a value. Once a constant is declared, it cannot be modified or assigned a new value. You declare a constant within a procedure or in the declarations section of a module, class, or structure.


1 Answers

That's not possible. In a constant record declaration, the member values must be constant expressions. That is, you cannot use typed constants as you have attempted to do.

The documentation says it like this, with my emphasis:

Record Constants

To declare a record constant, specify the value of each field - as fieldName: value, with the field assignments separated by semicolons - in parentheses at the end of the declaration. The values must be represented by constant expressions.

So you need to declare it like this:

const
  identity: TMatrix3D = (Index:
    ((x: 1; y: 0; z: 0),
     (x: 0; y: 1; z: 0),
     (x: 0; y: 0; z: 1))
    );

Frustrating to have to repeat yourself, but this is the best you can do I suspect.

like image 103
David Heffernan Avatar answered Sep 19 '22 12:09

David Heffernan