Studio/Rank

From J Wiki
Jump to: navigation, search

Rank specifies the behaviour of a verb on certain subarrays of its arguments, which for a rank-k verb are referred to as the k-cells. Each verb is assigned a rank, and a rank may be otherwise specified with the rank conjunction.

The verb < (box) is useful for illustrating rank. < boxes its argument, and has unbounded rank, which means it boxes its entire argument:

   ]n=. i.2 3 4
 0  1  2  3
 4  5  6  7
 8  9 10 11

12 13 14 15
16 17 18 19
20 21 22 23

   <n                  NB. box n (entire array)
+-----------+
| 0  1  2  3|
| 4  5  6  7|
| 8  9 10 11|
|           |
|12 13 14 15|
|16 17 18 19|
|20 21 22 23|
+-----------+

   <"2 n                NB. box the 2-cells (tables)
+---------+-----------+
|0 1  2  3|12 13 14 15|
|4 5  6  7|16 17 18 19|
|8 9 10 11|20 21 22 23|
+---------+-----------+

   <"1 n                NB. box the 1-cells (rows)
+-----------+-----------+-----------+
|0 1 2 3    |4 5 6 7    |8 9 10 11  |
+-----------+-----------+-----------+
|12 13 14 15|16 17 18 19|20 21 22 23|
+-----------+-----------+-----------+

   <"0 n                NB. box the 0-cells (atoms)
+--+--+--+--+
|0 |1 |2 |3 |
+--+--+--+--+
|4 |5 |6 |7 |
+--+--+--+--+
|8 |9 |10|11|
+--+--+--+--+

+--+--+--+--+
|12|13|14|15|
+--+--+--+--+
|16|17|18|19|
+--+--+--+--+
|20|21|22|23|
+--+--+--+--+

Here is +/ (sum), also of unbounded rank, applied to the same argument:

   sum=. +/

   sum n                NB. sum n
12 14 16 18
20 22 24 26
28 30 32 34

   sum"2 n              NB. sum the 2-cells
12 15 18 21
48 51 54 57

   sum"1 n              NB. sum the 1-cells
 6 22 38
54 70 86

Unbounded rank means maximum rank applicable, which in this case is 3, since n has rank 3. Thus (sum n), (sum"3 n) and (sum"_ n) are all the same. Negative rank r means positive rank a+r where a is the rank of the argument. Thus

   sum"_1 n             NB. sum 2-cells (3+_1)
12 15 18 21
48 51 54 57

   sum"_2 n             NB. sum 1-cells (3+_2)
 6 22 38
54 70 86

The composition conjunctions @ (atop) and @: (at) differ in the ranks of the result. The rank of u@v is the rank of v; the rank of u@:v is unbounded. A common mistake is to use the wrong one:

   ]n=. 1 2;10 20
+---+-----+
|1 2|10 20|
+---+-----+

   +/@> 1 2;10 20       NB. add up each item of n
3 30                    NB. rank 0, since > has rank 0

   +/@:> 1 2;10 20      NB. add up items of n (rank _)
11 22

Here rank is used to specify how two arrays are joined together:

   ]a=.'XYZ'
XYZ
   ]b=. >;:'bat cat dat'
bat
cat
dat

   a,b                  NB. append a to b
XYZ
bat
cat
dat

   a,"1 1 b             NB. append rows of a to rows of b
XYZbat
XYZcat
XYZdat

   a,"0 1 b             NB. append atoms of a to rows of b
Xbat
Ycat
Zdat

   a,"1 0 b             NB. append rows of a to atoms of b
XYZb
XYZa
XYZt

XYZc
XYZa
XYZt

XYZd
XYZa
XYZt

   a,"0 0 b             NB. append atoms of a to atoms of b
Xb
Xa
Xt

Yc
Ya
Yt

Zd
Za
Zt