Vocabulary/tilde

From J Wiki
Jump to: navigation, search

>> <<   Back to: Vocabulary Thru to: Dictionary

~ Reflex Adverb

Rank Infinity -- operates on x and y as a whole -- WHY IS THIS IMPORTANT?



(u~ y) is the same as (y u y)

u is executed as a dyad with x=y

   +~ 1 2 3
2 4 6

Common uses

1. Produce a operator table

avoids having to specify the same noun as both left and right arguments

   */~ i.10   NB. instead of: (i.10) */ (i.10)
0 0  0  0  0  0  0  0  0  0
0 1  2  3  4  5  6  7  8  9
0 2  4  6  8 10 12 14 16 18
0 3  6  9 12 15 18 21 24 27
0 4  8 12 16 20 24 28 32 36
0 5 10 15 20 25 30 35 40 45
0 6 12 18 24 30 36 42 48 54
0 7 14 21 28 35 42 49 56 63
0 8 16 24 32 40 48 56 64 72
0 9 18 27 36 45 54 63 72 81

2. Sort an array.

Sort x /: y is defined as sorting x into the order specified by y. To sort an array into ascending order, x and y must be the same, so use /:~

   /:~ 3 1 4 1 5 9 2 6 5 3 5
1 1 2 3 3 4 5 5 5 6 9

3. Self-classify.

To find the sets of identical items, use i.~ y which looks for each item of y within y itself. The result will split y into classes of identical values:

   pi =: 3 1 4 1 5 9 2 6 5 3 5   NB. A list

   ]classes =: i.~ pi  NB. a class for each item
0 1 2 1 4 5 6 7 4 0 4
   pi ,: classes    NB. classes shown beneath items
3 1 4 1 5 9 2 6 5 3 5
0 1 2 1 4 5 6 7 4 0 4

4. Apply u on sets of identical items of y. Use u/.~ y which applies u to each set of identical items. One thing you could do is count them:

   pi =: 3 1 4 1 5 9 2 6 5 3 5
   (~. pi) ,: #/.~ pi  NB. Show counts beneath the unique values
3 1 4 5 9 2 6
2 2 1 3 1 1 1


~ Passive Adverb

Rank -- depends on the rank of u -- WHY IS THIS IMPORTANT?



Swaps the arguments of a dyad. Thus, x f~ y is the same as y f x .

x u~ y is never necessary, since you can achieve the same effect with parentheses, but it can make code shorter or easier to read.


Common uses

1. x u~ y will save parentheses if you would need parentheses around y in y u x.

   boxedline =: <'A line of text'
   (> boxedline) , CRLF  NB. Unbox text and append CRLF
A line of text

   CRLF ,~ > boxedline   NB. Same effect without parentheses
A line of text

2. u~ can avoid the use of [ and ] in tacit forms:

   5 (+:@[ + ]) 10   NB. Double x and add to y
20
   5 (+~ +:)~ 10   NB. Same without []
20

3. J style is for dyads to accept "data" as y, with "control information" as x. x u~ y can be used if a verb is mis-specified, or if you want the other order. Examples of J primitives that are backwards for historical reasons are %, e., -, and -.

   'abcde' i. 'ef'   NB. Find index of y in x
4 5
   'abcde' e.~ 'ef'  NB. is y in x?
1 0

4. /:~~ is a cute trick:

  • the monad /:~~y is equivalent to y /: y, i.e. it sorts y
  • the dyad x /:~~ y is equivalent to x /: y, i.e. it sorts x into the order specified by y .