I have a 2×3 array
a =. 2 3 $ 2 3
a
2 3 2
3 2 3
And I want to add all the elements together using +/ to get 15.
So
+/a
5 5 5
Hmmm. This is clearly adding columns. I know that +/ rank is _ _ _ (i.e. infinity) and a is rank 2. I can’t translate this into imagining why it adds columns, unfortunately. (I am reading “J for C Programmers”)
So just for fun I did:
+/"1 a
7 8
So now it’s adding rows. Clearly I changed the rank of +/ to 1, which is less then 2 (the rank of a) which means… I don’t know. Why am I now adding rows by switching form infinity to 1?
What about
+/"0 a
2 3 2
3 2 3
So now we are just adding single cells with nothing so we get an array equal to the original a. Again I don’t know why, although I can just about muddle through an argument to get here: verb rank is less than a (the noun) rank, so we use this value, which is zero, so we add 0-cells, ie. we add each cell in turn individually.
And once more for luck:
+/"2 a
5 5 5
And I’m adding columns again. I don’t know the mechanism which is choosing which rows/columns/cells get added as the verb rank is changed. We’re adding columns but form my point of view, we could just as easily be adding rows.
I would like this explained if possible. As I said I’m reading some literature but I’m still finding it tough.
When you have an n-array, you can access each nesting “level” using the appropriate rank.
Ranks/shapes of a NOUN
First you have atoms (rank 0):
their shape (
$a) is empty.Then you have lists (rank 1), which are just some atoms put together:
their shape (
$b) is the length of the list.Then, tables (rank 2): lists put together (stiched or otherwise):
their shape is a 2 item list: rows, columns.
Then, up to rank-n array (rank n).
Rank of a VERB
The rank of a verb is a somewhat different story. It’s the rank on which the verb will apply. So, when you box-0 (
<"0) a noun, you always box the atoms of this noun, when you box-1 (<"1), you always box the lists of the noun, etc. Eg:0-rank:
1-rank:
2-rank:
3 rank:
In this example, ranks higher than 3 are the same as 3.
You can also use negative ranks, btw, which count backwards from the highest rank.
You can also mix the ranks.
Summing
You can see now, how changing the rank of
+/, changes the result of the summation. For example,+/"1sums every rank-1 list:To sum a rank-n array you have to perform n
+/s:or you can ravel (
,) the array before summing: