Tuesday, March 07, 2006

Operating with operators

Let's do a quick review of operators in Freya. Operators must be declared, as usual, in public static sections:
static public
method+(c1, c2: Complex): Complex;
operator-(c1, c2: Complex): Complex;
As you see, method and operator are equivalent when defining a "symbolic" operator. No syntax ambiguity arises in these cases, and the method keyword is friendlier, in my humble opinion.
However, operator is required when the operator name is a keyword or an identifier:
    operator True(c: Complex): Boolean;
Technically, True is an operator in Freya, following C#. We cannot proceed as in Pascal and consider True an enumerative constant, since in that case, both Freya and C# would require the class name as qualifier: Boolean.True.
Even when the operator name is a keyword, there's no syntactic ambiguity. The real reason for keeping the operator keyword is this:
    operator Explicit(c: Complex): Double;
operator Implicit(d: Double): Complex;
Though both explicit and implicit are C# keywords, they are not keywords in Freya. We could have allowed this:
   method Explicit(c: Complex): Double;
But I thought it would be dangerous, since you cannot tell whether the programmer intention was declaring a full featured operator or a regular method called Explicit.
Operator implementation is straightforward, as usual:
implementation for Complex is

operator Implicit(d: Double): Complex;
begin
Result := new Complex(d, 0.0);
end;

Labels: ,

0 Comments:

Post a Comment

<< Home