Vocabulary/RankInfoIsImportant

From J Wiki
Jump to: navigation, search

Why is the rank of a verb important to know?

Back to: Vocabulary

J primitives work not just on single numbers and letters, but on arrays of these: a rare thing among computer languages. This capability naturally extends to user-written functions (verbs, including verbs formed with adverbs and conjunctions).

This is terrifying if you think about it. Does that mean that every verb you write has to handle arrays of arbitrary rank?

No! When you write a verb, it has a verb rank which tells the maximum rank of operand(s) the verb can handle. Any operand of higher rank is automatically chopped up into cells whose rank does not exceed the rank of the verb. The results of applying the verb on the cells are collected into the final result of the verb.

Most verbs have as small a rank as possible to take maximum advantage of this automatic repetition. For example, the arithmetic verbs, like +, have rank 0 because they can operate on atoms individually.

Thus, when you execute

   100 200 300 + 1 2 3
101 202 303

it looks like two lists are being added together, but actually the addition is being performed atom-by-atom, because of the rank of +.

The rank at which a verb is applied can change the result. That wouldn't be true for a verb like +: y, which simply doubles y, but what about +/ y, which adds up the items of y? If it has infinite rank, the items are lists, and you get the sum of all the lists:

   i. 3 4
0 1  2  3
4 5  6  7
8 9 10 11
   +/"_ i. 3 4
12 15 18 21

But if it has rank 1, it is applied to each list in the operands, adding up the atoms in the list:

   +/"1 i. 3 4
6 22 38

Suppose we didn't assign a rank: what would the rank of +/ by itself be? Ah, that's why you need to learn the ranks of the primitives. Every primitive has a rank, and the modifiers do too. Some modifiers set a fixed rank, but some produce a verb whose rank depends on the modifier's operands.

For example, the conjunction @: produces a verb that has infinite rank, but the very similar conjunction @ creates a verb whose rank depends on the rank of its operands. The difference can be enormous.

To find the Pythagorean length of a vector you might execute

  %: +/ *: 3 4
5

Square the numbers, add them, and take the square root. But then you learn a little about the @ conjunction, and you try to rewrite the sentence as

   %:@(+/)@*: 3 4
3 4

What happened? It was the rank. You created a verb whose rank was 0 and it was executed on each atom individually. You should have written

   %:@:(+/)@:*: 3 4
5

You can learn more about the rank of modifiers here.