Next: Rules for code Up: Implementation Previous: Implementation

The precedence of operators and operator syntax

Parentheses can be used in order to specify a precedence for the order of evaluation of operations in a computation. For example, the expression !a==b parses as Not[Equal[a,b]] which is converted to Unequal[a,b]. Whereas, (!a)==b parses as Equal[Not[a],b] which is entirely different. A code translation package is practically useless if it does not produce code that obeys the operator precedence of the target language. Fortunately, most cases are dealt with correctly by Mathematica's format functions, since they simply correspond to the operator precedence in that language. This is not always immediately obvious. For example, what is the order of precedence in the expression a^b^c? In fact this is evaluated as a^(b^c) and correctly interpreted in FORTRAN without parentheses. Unfortunately, there are cases where Mathematica's syntax for operators does not produce correct target language code.

For example, logical operators can be specified with multiple arguments in Mathematica. FortranForm is unable to translate these and returns syntactically incorrect output.


In[4]:= FortranForm[ a>b>c ]
Out[4]//FortranForm=
Greater(a,b,c)
In contrast, FortranAssign knows about such operators and performs some transformations to manipulate the expressions into appropriate form.

In[5]:= FortranAssign[ a>b>c ]
Out[5]//OutputForm=
        (a.gt.b).and.(b.gt.c)
Some cases are not so obvious and require additional subtlety, because they do not obey the law of transitivity: If and then .


In[6]:= FortranAssign[a!=b!=c]
Out[6]//OutputForm=
        (a.ne.b).and.(a.ne.c).and.(b.ne.c)
In fact there are other examples when translation of relatively simple relational statements is inaccurate. The following example illustrates this for the Inequality construct.


In[7]:= FortranForm[ a>b<c ]

Out[7]//FortranForm=
Inequality(a,Greater,b,Less,c)
Translation of expressions involving Inequality is possible with the Assign functions.


In[8]:= FortranAssign[ a>b<c ]

Out[8]//OutputForm=
        (a.gt.b).and.(b.lt.c)


bondaren@thsun1.jinr.ru