A Brief J Reference This brief reference gives informal descriptions of most of the J primitives. Not every primitive is included and some idioms, examples and other resources have been added where appropriate. Since the presentation is brief and informal, it is not a replacement for the main J references: the J Introduction and Dictionary, the J User manual and the J Primer. However, since the material is informally organized by topic, this reference may be useful when considering which J features might be relevant to a given problem. Some users may also find it helps locate gaps in knowledge that can then be filled in with the main references. Chris Burke Jsoftware Inc. cburke@jsoftware.com www.jsoftware.com Cliff Reiter Department of Mathematics Lafayette College webbox.lafayette.edu/~reiterc Last updated August 2014 for J802. 2 Contents A Brief J Reference 1 Language Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 Nouns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 Basic Arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 Boolean and Relational Verbs . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 Name Assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 Data Information and Building . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 Data Copying . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 Data Indexing and Amendment . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 Boxed Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 Rank . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 Explicit Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 Tacit Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 Verb Application to Subsets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 Gerunds and Controlled Application of Verbs . . . . . . . . . . . . . . . . . . . 16 Program Flow Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 Function Composition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 More Verbs from Verbs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 Conversion: Literal, Numeric, Base, Binary . . . . . . . . . . . . . . . . . . . . . 21 Reading and Writing Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 Sorting and Searching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 Efficiency, Error Trapping, and Debugging . . . . . . . . . . . . . . . . . . . . . 25 Randomization and Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 Constant and Identity Verbs . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 6 6 7 8 8 9 9 10 11 11 11 12 13 13 14 16 17 19 19 20 21 22 22 23 23 CONTENTS 27 Exact Computations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 Number Theory and Combinatorics . . . . . . . . . . . . . . . . . . . . . . . . . 29 Circular and Numeric Verbs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 Complex Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 Matrix Arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 Calculus, Roots and Polynomials . . . . . . . . . . . . . . . . . . . . . . . . . . 33 Special Datatypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 Qt Session Manager Short-Cut Keys . . . . . . . . . . . . . . . . . . . . . . . . 36 Addons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37 Parts of Speech and Grammar . . . . . . . . . . . . . . . . . . . . . . . . . . . 38 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 Vocabulary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 24 24 25 25 26 26 27 28 28 29 30 31 32 4 A Brief J Reference 5 1 Language Basics Examples: fahrenheit =: 50 (fahrenheit - 32) * 5%9 10 prices=: 3 1 4 2 orders=: 2 0 2 1 orders * prices 6 0 8 2 +/ orders * prices 16 +/ \ 1 2 3 4 5 1 3 6 10 15 2 3 * / 1 2 3 4 5 2 4 6 8 10 3 6 9 12 15 cube=: ^&3 cube i. 9 0 1 8 27 64 125 216 343 512 Names 50 fahrenheit + - * % / \ & ( ) =: Nouns Verbs Adverbs Conjunction Punctuation Assignment • Verbs act upon nouns (their arguments) to produce noun results • A verb may have two distinct (usually related) meanings depending on whether it is applied to one argument (to its right), or to two arguments (left and right). • An adverb acts on a single noun or verb to its left, typically returning a verb. For example: +/ is a verb that sums its argument. • A conjunction applies to two arguments, either nouns or verbs, typically returning a verb. In the example above, ^&3 is the verb cube. A Brief J Reference 6 2 Nouns Nouns are classified in three independent ways: • numeric or literal • open or boxed • arrays of various ranks The atoms of any array must belong to a single class: numeric, literal, or boxed. Arrays of ranks 0, 1, and 2 are also called atom, list, and table, or, in mathematics, scalar, vector, and matrix. A single entity such as 2.3 or ’A’ is called an atom. The number of atoms in the shape of a noun is called its rank. Each position of the shape is called an axis of the array, and axes are referred to by indices 0, 1, 2, etc. Boxed nouns are produced by the verb < (box). The result of box is an atom, and boxed nouns are displayed in boxes. Box allows one to treat any array (such as the list of letters that represent a word) as a single entity, or atom. 3 Constants r b e p x x j ad ar a. a: _1 _ __ _. rationals; 5r4 is 5 4 base representations; 2b101 is 5 base 10 exponential notation (scientific notation); 1.2e14 is 1.2 × 1014 base π exponential notation; 3p6 is 3π6 base e exponential notation; 3x2 is 3e2 extended precision; 2^100x is the exact integer 2100 complex numbers; 3j4 is 3 + 4i angle in degrees; 1ad45 is approximately 0.707j0.707 angle in radians; 1ar1 is ^0j1 alphabet; list of all 256 ASCII characters boxed empty negative one (−1) infinity (∞) negative infinity (−∞) indeterminate 7 4 Basic Arithmetic x + y + y x - y - y x * y * y x % y % y +: y -: y *: y x %: y %: y x ^ y ^ y x ^. y ^. y x | y | y x plus y y; identity function for real y, conjugate for complex y x minus y negate y x times y signum of y is _1, 0 or 1 depending on the sign of real y x divide y reciprocal of y double y halve y square y xth root of y square root of y x to the power y exponential base e base x logarithm of y natural logarithm (base e) residue (remainder); y mod x absolute value of y x <. y minimum of x and y; (smaller of, lesser of ) <. y greatest integer less than or equal to y; called the floor x >. y maximum of x and y; (larger of, greater of ) >. y <: y >: y least integer greater than or equal to y; called the ceiling predecessor of y; y-1 (decrement) successor of y; y+1 (increment) 8 A Brief J Reference 5 Boolean and Relational Verbs Result of tests are 0 if false or 1 if true. x < y x <: y x = y x >: y x > y x ~: y x -: y test if x is less than y test if x is less than or equal to y test if x is equal to y test if x greater than or equal to y (larger than or equal ) test if x is greater than y (larger than) test if x is not equal to y test if x is identically same as y (match) -. y not y; 1-y for numeric y. x +. y x *. y x +: y x *: y x e. y e. y x or y; the greatest common divisor (gcd ) of x and y x and y; the least common multiple (lcm) of x and y x nor y (not-or ) x nand y (not-and ) test if x is an item in y (member of ) test if the raze is in each open x E. y mark beginnings of list x as a sublist in y (pattern occurrence) Boolean tests are subject to a default comparison tolerance of t=:2^_44. For example, x=y is 1 if the magnitude of the difference between x and y is less than t times the larger of the absolute values of x and y. The comparison tolerance may be modified with the fit conjunction, !., as in x=!.0 y, tests if x and y are the same to the last digit. 6 Name Assignment abc=: 1 2 3 abc=. 1 2 3 'abc'=: 1 2 3 'a b c'=: 1 2 3 'a b'=: 1 2;3 cube=: ^ & 3 (exp)=: 1 2 3 names '' erase 'a b c' (4!:5) 1 global assignment of 1 2 3 to name abc local assignment of 1 2 3 to name abc. The value is only available inside the definition where it is made. indirect assignment of 1 2 3 to name abc parallel assignment of 1 to a, 2 to b and 3 to c. parallel unboxed assignment of 1 2 to a and 3 to b function assignment result of expression exp is assigned 1 2 3 list of names defined in current locale erases the names a, b, and c (snap) returns names changed since last execution of (4!:5) 1 Several foreign conjunctions of the form 4!:n deal with names. See also the Locales lab to learn about using locales to create different locations for global names. 9 7 Data Information and Building # y $ y x $ y i. y i: y i: a j. b x F/ y x , y x ,. y x ,: y , y ,. y ,: y $. y number of items in y (tally) shape of array y shape x reshape of y (cyclically using/reusing data) list of indices filling an array of shape y (integer ); negative y reverses axis symmetric arithmetic sequence; for integer y, the integers from -y to y list of numbers from -a to a in b equal steps table of values of dyad F with arguments from x and y (outer product) append x to y where axis 0 is lengthened (catenate) stitch x beside y (append items) where axis 1 is lengthened; x laminated to y giving an array with 2 items ravel (string out) elements of y ravel items of y itemize, make y into a single item by adding a new length-1 leading axis sparse matrix representation of y 8 Data Copying x # y x #^:_1 y (G # ])y x {. y {. y {: y x }. y }. y }: y |: y (<0 1) |: y replicate or copy items in y the number of times indicated by x; the imaginary part of x is used to specify the size of expansion with fill elements expand (inverse of #) selects items of y according to 1 in Boolean x, pads with fills where 0 in x selects elements of y according to Boolean test G; thus, (2&< # ]) y gives the elements of y greater than 2. shape x take of y; negative entries cause take from end of axes; entries larger than axis length cause padding with fill elements. item in 1 {. y for non-empty arrays; in general 0{y (called head ) item in _1{.y or _1{y (called tail ) drop shape x part of y; negative entries cause drop from end of axes. 1 }. y (one drop) or behead _1 }. y (negative one drop) or curtail transpose of y trace (diagonal) of matrix y 10 A Brief J Reference 9 Data Indexing and Amendment I { y x I } y item at position I in y (index or from) Arrays of I give corresponding arrays of items. Boxed arrays I give positions on corresponding axes. An empty box gives all values along that axis. y amended at positions I by data x [A=: i.3 4 0 1 2 3 4 5 6 7 8 9 10 11 0 2 { A 0 1 2 3 8 9 10 11 0 2 {"1 A 0 2 4 6 8 10 (<0 2;3) { A 3 11 1000 (<0 2;3) } A 0 1 2 1000 4 5 6 7 8 9 10 1000 11 10 Boxed Arrays box y open (unbox) y one level link x and y; box x and append to y; if y is unboxed, then box y first raze y; remove one level of boxing apply F inside of each boxed element of y apply F to inside of each boxed element of y and adjoin the results. boxed empty (noun called ace) boxed list of J words in string y; (word formation) depth or deepest level of boxing in y apply F at level n and maintain boxing. May be used dyadically and left and right level specified. If boxing is thought of as creating a tree structure, then adverb L: 0 may be called leaf apply F at level n and list the result (spread ) map has the same boxing as y and gives the paths to each leaf fetch the data from y specified by the path x < y > y x ; y ; y F &.> y F &> y a: ;: y L. y F L: n y F S: n y {:: y x {:: y 11 Rank Rank can be specified by one, two or three numbers. If the rank r contains three numbers, the first is the monadic rank, the second the left dyadic rank and last the right dyadic rank. If it contains two numbers, the first gives the left dyadic rank and the second gives the monadic and right dyadic rank. All the ranks are the same when a single number is given. F"r y x F"(lr,rr) y x F"0 _ y N"r F b. 0 apply F on rank r cells of the data y apply F on rank lr cells from x and rank rr cells from y table builder when F is a scalar function constant function of rank r and result N gives the monadic, left and right ranks of the verb F 12 Explicit Definition Explicit definitions can be made with m : n where m is a number that specifies whether the result is a noun, verb, adverb or conjunction. When n is 0, successive lines of input give the defining expressions until an isolated, closing right parenthesis is reached. Noun arguments to adverbs and conjunctions may be specified by m on the left and n on the right. Verb arguments are u and v and the derived functions use x and y to denote their arguments. 4 : 0 3 : 0 2 : 0 1 : 0 0 : 0 input mode for a dyadic verb input mode for general verb. This is the monadic definition, optionally followed by an isolated colon and the dyadic definition. input mode for conjunction input mode for an adverb input mode for a noun 12 A Brief J Reference The right argument n as in m : n, may be a string, a CRLF delimited string, a matrix, or a boxed list of strings. For example: f=: 3 : '(*:y) + ^y' defines f (y) = y2 + ey 13 : n converts to tacit form of a verb (if possible). For example: 13 : 'x , 2 * x + y' [ , 2 * + 13 Tacit Definition In a tacit definition the arguments are not named and do not appear in the definition. In many cases the tacit form of definition is much simpler and more obvious than the equivalent explicit definition. For example: plus=: + sum=: +/ max=: >./ mean=: +/ % # assigns name plus to + sum of numeric list maximum of numeric list average of numeric list Compare the last definition with an equivalent explicit definition: mean=: 3 : '(+/y) % #y' 13 14 Verb Application to Subsets F/ y G\ y F/ \ y x G\ y G\. y x G\. y x G;._3 y G;.3 y G;._2 y x F/. y F/. y insert verb F between items of y, also called F-reduction; thus +/2 3 4 is 2+3+4 apply G to prefixes of y; generalized scan F scan of y apply G to sublists of length x in y (the lists are infixes); negative x gives non-overlapping sublists. For example x avg y gives length x moving averages of data in y (where avg=: +/ % #). apply G to suffixes of y (order of execution makes this fast!) apply G to lists where sublists of length x in y are excluded (the sublists are outfixes) cut; apply G to shape x tessellations of y. In general, the rows of x give the shape and offset used for the tessellation. Include shards by specifying 3 instead of _3. cut; generalized suffix cut; apply G to sublists marked by ending with the last item in y. So }:<@}:;._2 y,CRLF gives the boxed lines of CRLF delimited text y. G;.2 y includes marked positions in sublists. G;._1 y and G;.1 y use first item to mark beginnings of sublists. G;.0 y and dyads and gerunds G are also defined. function F is applied to parts of x selected by distinct items (keys) in y. For example #/.~ y gives frequency of occurrence of items of y apply F to oblique lists from y. 15 Gerunds and Controlled Application of Verbs ^: F^:n y F^:_ y F^:(i.n)y F^:G^:_ y F`G F/. y F`:0 y F@.G F::G iterate function (power ) iterate F n times on y; see the Dictionary for gerund n iterate F until convergence (limit) result of F iterated 0 to n-1 times on y iterate F on y until G gives false tie verbs F and G together forming a gerund evaluate each verb in gerund F taken cyclically on data y (evoke gerund ) alternative form of evoke gerund, returning all combinations of functions from F on y agenda: use G to select verb from gerund F to apply adverse: apply F, if an error occurs, apply G instead Many adverbs and conjunctions have gerund meanings that give generalizations; e.g. gerund insert cyclically inserts verbs from the gerund. Thus, the following are the same: +`% / 1 2 3 4 1 + 2 % 3 + 4 14 A Brief J Reference 16 Program Flow Control Execution control is provided by words such as: if. else. while. etc. These control words: • can occur anywhere in a line of code • group the code into blocks Here, a block is zero or more sentences, which may themselves contain control words. A J block is true if the first element of the result is not zero. In particular, an empty block is true. In all cases, the result of the last expression executed that was not a test, is returned as the verb result. if. elseif. signum=: 3 : 0 if. y < 0 do. _1 elseif. y=0 do. 0 elseif. do. 1 end. ) signum &> _5 7 8 0 _1 1 1 0 Compare: * _5 7 8 0 _1 1 1 0 select. The select. control word allows execution of expressions when a value matches those in a given case or cases. Evaluation of the select. control structure then terminates for a case. statement, or continues with the next block for an fcase. statement. An empty case matches all. 15 atype=: 3 : 0 select. #$y case. 0 do. 'scalar' case. 1 do. 'vector' case. do. 'array of dimension greater than 1' end. ) atype dc11.2' (8!:2) 1.23 12345 0.123,__ 0 _1234.5,:_44 0.5 0.1 1.23 12,345.00 0.12 nil -1,234.50 0.10 0.50 n/a -44.00 See also the Foreign Conjunction help. 20 A Brief J Reference 21 Reading and Writing Files The following verbs are based on foreign conjunctions in the form 1!:n. These provide for file reading/writing including indexed reads and writes and creating directories, reading and setting attributes and permissions. Chopping file data in appropriate places can be accomplished with ;._2 (cut). Simple substitution (e.g., _ for -) may be accomplished with charsub from strings. See regex for more complex processing. Memory mapped files should be considered for huge data sets. 1!:0 y 1!:1 y x 1!:2 y x 1!:3 y 1!:11 y x 1!:12 y For example: directory information matching path and pattern in y (see fdir) read file y specified by a boxed name (see fread and freads) write file y with raw, (a. or text) data x (see fwrite and fwrites) append file y with raw, a. or text data x (see fappend and fappends) indexed read. y is a pair: file name; index and length. The index may be negative. If the length is elided, the read goes to the end. indexed write. y is a pair: file name; index. 'abcdefgh' 1!:2 Open • Larger Than _ Negative Sign, Infinity + Conjugate • Plus * Signum • Times - Negate • Minus % Reciprocal • Divide ^ Exponential • Power $ Shape Of • Shape ~ Reflex • Pass, Evoke | Magnitude • Residue . Det • Dot Product : Explicit (monad, dyad) , Ravel • Append ; Raze • Link # Tally • Copy ! Factorial • Out Of / Insert • Table, Insert \ Prefix • Infix, Train [ Same • Left ] Same • Right { Catalogue • From } Item Amend • Amend " Rank • Constant ` Tie (gerund) @ Atop & Bond, Compose ? Roll • Deal a. Alphabet b. Boolean, Basic D. Derivative E. • Member Of Interval i. Integers • Index Of j. Imaginary • Complex M. Memo p. Roots • Polynomial =. Is (local) <. Floor • Lesser Of >. Ceiling • Larger Of _. Indeterminate =: Is (global) <: Decrem • Less Or Equal >: Increm • Larger Or Equal _: Infinity +. Real/imaginary • GCD (Or) *. Length/angle • LCM (And) -. Not (1-) • Less %. Mat Inv • Mat Divide +: Double • Not Or *: Square • Not And -: Halve • Match %: Square Root • Root ^. Natural Log • Logarithm $. Sparse ~. Nub |. Reverse • Rotate ^: Power $: Self Reference ~: Nub Sieve • Not Equal |: Transpose .. Even :. Obverse ,. Ravel Items • Stitch ;. Cut .: Odd :: Adverse ,: Itemize • Laminate ;: Words • Sequential Machine #. Base 2 • Base !. Fit /. Oblique • Key, Append \. Suffix • Outfix #: Antibase 2 • Antibase !: Foreign /: Grade Up • Sort Up \: Grade Down • Sort Down {. Head • Take }. Behead • Drop ". Do • Numbers @. Agenda &. &.: Under (Dual) ?. Roll • Deal (fixed seed) a: Ace (Boxed Empty) C. Cycle Direct • Permute D: Secant Slope f. Fix [: Cap {: Tail, {:: Map, Fetch }: Curtail ": Default Format • Format `: Evoke Gerund @: At &: Appose A. Anagram Index • Anagram d. Derivative e. Raze In • Member In H. Hypergeometric i: Axis Integers • Index Of Last L. Level Verb NB. Comment p.. Poly Deriv • Poly Integral I. Indices • Interval Index L: Level At o. Pi Times • Circle Function p: Primes q: Prime Factors • Prime Exponents S: Spread T. Taylor Approximationu: Unicode _9: to 9: Constant Verbs r. Angle • Polar t. Taylor Coeff. (m t. u t.) x: Extended Precision s: Symbol t: Weighted Taylor Font styles in the Vocabulary: noun, verb, adverb, conjunction.