Order of evaluation
What is the answer if the parentheses are left out?
10 - 4 - 3
J evaluates the sentence as:
10 - (4 - 3)
Most other languages would evaluate it as:
(10 - 4) - 3
In the absence of parentheses, J implicitly provides them from the right towards the left. Other languages provide them from the left towards the right. A longer sentence will make this visually clearer.
10 - 4 - 3 - 1
10 - (4 - (3 - 1)) NB. J right-to-left
((10 - 4) - 3) - 1 NB. others left-to-right
Now consider a sequence of monadic verbs.
- - - 4
Everyone knows how to parenthesize this, and every language does it the same.
- (- (- 4))
The grouping is done right-to-left and in this case the other languages agree with J. J always parenthesizes from right-to-left, whereas other languages have different rules for different situations.
J has a right-to-left order of evaluation. Most other languages have a left-to-right order of evaluation for dyads, right-to-left for monads; and this is modified by the relative precedence of the verbs involved.
With nouns and verbs the J evaluation rule from J Dictionary section E is:
Execution proceeds from right to left, except that when a right parenthesis is encountered, the segment enclosed by it and its matching left parenthesis is executed, and its result replaces the entire segment and its enclosing parentheses.
There are things in J, other than nouns and verbs, that you have not yet met that complicate this rule by adding a few more. It is these additional classes that largely justify the J break with tradition and adoption of a right-to-left evaluation.To further quote from the J Dictionary section E:
One important consequence of these rules is that in an unparenthesized expression the right argument of any verb is the result of the entire phrase to its right.
This is due to the lack of verb precedence as well as right-to-left evaluation.
No verb precedence, right-to-left evaluation, and the rules for the other classes make the overall evaluation rules simple, reduce the need for parentheses, and make sentences easier for an experienced J user to read and write.
Read the following sentences, evaluate them in your head, and understand how the no precedence and right-to-left rules explain the answer.
2 * 4 + 5
2 + 4 * 5
2 - 4 - 5
8 % 2 + 2
Remember: no verb precedence and right-to-left evaluation.