REBOL 3 Docs Guide Concepts Functions Datatypes Errors
  TOC < Back Next >   Updated: 6-Feb-2009 Edit History  

REBOL 3 Concepts: Math: Evaluation Order

Pending Revision

This document was written for R2 and has yet to be revised for R3.

There are two rules to remember when evaluating mathematical expressions:

The evaluation of expressions from left to right is independent of the type of operator that is used. For example:

print 1 + 2 * 3
9

In the example above, notice that the result is not seven, as would be the case if multiplication took precedence over addition.

Important Note

The way mathematical expressions are evaluated from left to right regardless of the operator is different than many other computer languages. Many languages have rules of precedence that you must remember that determine the order of evaluation of operators. For example, a multiply is done before an add. Some languages have 10 or more such rules.

In REBOL, rather than requiring users to remember the precedence of operators, you only need to remember the left-to-right rule. More importantly, for advanced code such as expressions that handle expressions (in reflection, for example) you do not need to reorder terms based on precedence. The evaluation order is kept simple.

For most math expressions, the left-to-right evaluation rule works quite well and is easy to remember. However, because this rule is different from other languages, it can be a source of programming errors, so watch out.

The best solution is to check your work. You can also use parentheses if necessary to clarify your expression (see below), and you can always type your expression at the console to verify your result.

If you need to evaluate in some other order, reorder the expression or use parentheses:

print 2 * 3 + 1
7
print 1 + (2 * 3)
7

When functions are mixed with operators, the operators are evaluated first, then the functions:

print absolute -10 + 5
5

In the above example, the addition is performed first, and its result is provided to the absolute function.

In the next example:

print 10 + sine 30 + 60
11
30 + 60 => 90
sine 90 => 1
10 + 1 => 11
print

To change the order such that the sine of 30 is done first, use parentheses:

print 10 + (sine 30) + 60
70.5

or reorder the expression:

print 10 + 60 + sine 30
70.5


  TOC < Back Next > REBOL.com - WIP Wiki Feedback Admin