15.4 Arithmetic operators

Arithmetic operators define the action of a binary operator. Possible operations are:

To multiply two types, the * multiplication operator must be overloaded.
To divide two types, the / division operator must be overloaded.
To add two types, the + addition operator must be overloaded.
To subtract two types, the - subtraction operator must be overloaded.
To exponentiate two types, the ** exponentiation operator must be overloaded.
Unary minus
is used to take the negative of the argument following it.
Symmetric Difference
To take the symmetric difference of 2 structures, the >< operator must be overloaded.

The definition of an arithmetic operator takes two parameters, except for unary minus, which needs only one parameter. The first parameter must be of the type that occurs at the left of the operator, the second parameter must be of the type that is at the right of the arithmetic operator. The result type must match the type that results after the arithmetic operation.

To compile an expression as

  R : real;  
  C,Z : complex;  

One needs a definition of the multiplication operator as:

Operator * (r : real; z1 : complex) z : complex;  
  z.re := z1.re * r;  
  z.im := z1.im * r;  

As can be seen, the first operator is a real, and the second is a complex. The result type is complex.

Multiplication and addition of reals and complexes are commutative operations. The compiler, however, has no notion of this fact so even if a multiplication between a real and a complex is defined, the compiler will not use that definition when it encounters a complex and a real (in that order). It is necessary to define both operations.

So, given the above definition of the multiplication, the compiler will not accept the following statement:

  R : real;  
  C,Z : complex;  

Since the types of Z and R don’t match the types in the operator definition.

The reason for this behavior is that it is possible that a multiplication is not always commutative. E. g. the multiplication of a (n,m) with a (m,n) matrix will result in a (n,n) matrix, while the multiplication of a (m,n) with a (n,m) matrix is a (m,m) matrix, which needn’t be the same in all cases.