Download For C Programmers - Trinity Computer Science Department
Transcript
(y i. x) { z , d
To evaluate the polynomial defined by x, so that if for example x is 2 1 5 the result
is 5y2+y+1:
+/ x * y ^ i. # x
(and now you can see why 0^0 is 1).
To evaluate the polynomial defined by x going the other direction, so that if for
example x is 2 1 5 the result is 2y2+y+5:
y #. x
The last example, due to Roger Hui, has a power and economy that amount to
sorcery. Suppose you had a list, and you wanted to know, for each item in the list, how
many identical items appeared earlier in the list. You could find out this way:
y =. 2 2 2 1 2 1 4 6 4 2
t - (i.~ y) { t =. /: /: y
0 1 2 0 3 1 0 0 1 4
Take a little time—maybe a long time—to see how this works. The /: /: y is an
idiom we discussed earlier—did you figure it out? It gives the ordinal of each item of y,
in other words the rank of the item among the items of y . If there are equal items, they
will occupy a block of successive ordinals. In this example you can see that t does
indeed hold the ordinals:
t
2 3 4 0 5 1 7 9 8 6
(i.~ y) takes the index of each item of y within y itself, in other words, for each item,
the index of the first item with the same value:
(i.~ y)
0 0 0 3 0 3 6 7 6 0
Since the identical items of y are a block of successive ordinals, and (i.~ y)
comprises indexes of first items in blocks, we can find relative positions in blocks by
subtracting the ordinal of the first item with a value from the ordinals of all the other
items with the same value. That is what this expression does. Lovely!
In addition to the foregoing ad hoc means of varying the operation cell-by-cell J has
some language features expressly designed for that purpose:
Power/If/DoWhile Conjunction u^:n and u^:v
u^:n y has infinite rank. It applies the verb u to y, then applies u to that result, and
so on, for a total of n applications of u, ; in other words u u u…(n times) y, as we
see when it is used with the >: (increment) primitive:
>: 5
6
>:^:2 (5)
7
>:^:3 (5)
8
fndisplay gives a picture of what is happening:
85