Note 'Literate J--Primitive-Aliases and Translation' Aliases for primitives Some users may prefer a more literate form of J, using words instead of the J primitives. We call the words alpha primitives, since they use an alphabetic form rather than a graphic or inflected graphic to represent them. This script provides a means of doing this, with multiple options for the words used, and verbs to convert a script in alpha form to a script in J primitives, to reduce execution time. The alphabetic and the graphic forms can be freely mixed in a script. This script assigns English names as used in the Vocabulary and Dictionary, with some commonly used alternates. The default is to use lowercase names, consistent with the practise in J libraries. These notes, however, use CamelCase--words with capitals at their beginnings, and possibly in their middles, with no spaces. That is consistent with the previous 'primitives' script in the distribution, and helps to avoid name conflicts. To use CamelCase, which helps reduce conflict with commonly chosen names, place NB. at the beginning of the lines invoking tolower following the line: gendefs ALIASES Names supplied here are generally not abbreviated unless they so appear in either the Vocabulary or Dictionary head words. Names which are duplicated in either source have been modified to give unique names. Modifications are: _: InfinityVerb ^ ToPower \: SortDown (instead of Sort) [ SameL (for monadic use) &.: UnderInfinite (the infinite-rank case for right argument) d. Derivative0 (with left term applied rank-0) Some common abbreviations for relations and booleans have been added, as have PowerBond for the left-argument use of &, named versions of the constant verbs, and some abbreviations and alternate names (including some used by Dr. Iverson). One extension, NegInfinityVerb, is a non-primitive "idiom" or "secondary" definition. A few other idioms have been included as samples, but it may be equally convenient to define others directly as J assignments. When using lowercase names, the verbs sort and table from the standard libraries will be hidden by new definitions. Few other standard-library verbs should be affected. The verbs max, min, cut, rotate and deal will also differ from verbs with these names in scripts 'stats', 'strings', 'isigraph' or 'random'. One anomaly in the analysis of literate-version expressions via their tree expansion by 5!:4 is that conjunctions and adverbs are displayed in their symbolic form, instead of in their alpha form; this can be confusing to a novice, and cryptic for anyone when a definition is not tacit. Idioms do remain intact. Some examples of usage 0. Using your own or foreign-language names: Persons wishing to have a set of primitives with other names, perhaps in another language, merely need to make additions to or replacements for the names supplied in the global variable EnglishNames, defined below. Name tables for other natural languages may be defined and appended to or used in place of this one. 1. To convert to primitive form a script saved in literal form as a noun, myscript , use: myscriptp =: toprimitives myscript 2. To convert a file from literal to graphics form: Suppose you have a script in file f written using the literal names and would like to write it to file f1 using primitives to obtain maximum execution speed. The verb toprimitives has a dyadic form which accepts as left argument the file name of a literate J script and as right argument the file name for the same script after conversion to J primitives: f toprimitives f1 3. To run a file written in literal form: If you have loaded this script, you may use the Run menu or key shortcuts. This will execute slower than when using the options below but, given the speed of most machines, this will often not matter. If you have saved the file with path and name f, you may use loada to load and convert a script which uses alpha primitives: loada f If you want to run the file and also display the output, use: loadad f 3. Conversion to literal: To convert a file using the standard form to alpha primitives is a more complex task. An article, "Primitives to Mnemonics", on the JWiki pages offers a script contributed by Don Guinn for this purpose. Visit: http://www.jsoftware.com/jwiki/Primitives_to_Mnemonics This version: alters the former "primitives" script to enforce the relevant monadic or dyadic interpretation of those verbs which correspond to the same ambiguous graphic symbol; they yield syntax or domain errors rather than unexpected values when used with the wrong number of arguments. Such protection is not provided for ambiguous non-verb symbols, except for the '&'-family, which could otherwise produce wierd results from "reasonable" tacit expressions. Another addition to this script is the listing of parts-of-speech flags with the defined names, as a further aid to learning proper syntax. An option which may be welcomed by speakers of highly inflected languages or students of another logically-designed language is to attach those flags to the names themselves: remove the NB. prefix from attachflags '' . A limited form of tracing, recording the arguments to each execution of a function, is implemented by Track. When called monadically, it empties the record in Tr_base_; dyadicly, it records a prefix of y labeled by x. The boxed record may be more compactly displayed via verb nobar. When defining aliases, an option is provided to build in tracing for the arguments to each execution, by removing NB. on three lines following the tolower invocations. The implementation of idiom names is based on a suggestion by Don Guinn. Revised by Art Anger, 2008-2009JAN ) NB. ========================================================= NB. Constructing definitions for implementing a literate form of script NB. and for transforming it to symbolic primitives. require 'files' cocurrent 'z' NB. Listing desired additional names for primitive symbols or idioms, as: NB. usage types (dyadic monadic) primitive symbol NB. dyadic (or non-verb) names(s) : monadic name(s) (if any) NB. Multiple-primitive idioms must be quoted (with internal quotes doubled) NB. and may be given dyadic and/or monadic distinctions when they take noun NB. arguments. NB. The colon should be entered even when names are entered on only one side. NB. No separating colon should be entered for non-verbs. NB. Usage types: N(oun) V(erb) A(dverb) C(onjunction) TestSample=: 0 : 0 N _. Indeterminate V _: InfinityVerb . V ~. : Nub V V + Plus : Conjugate A f. Fix A A / Table Insert A E ~ Evoke Reflexive Reflex Passive Swap C ^: Power C : MonadDyad ExplicitDefinition Explicit N '''''' Empty V '-@_:' NegInfinityVerb V V '+/' PlusTable : Sum Sigma . V '+/%#' : Average Mean V . '+/ .*' InnerProduct DotProduct : C '&.>' Each ) NB. Dy/Monad uses, Symbol(s), Dyadic (or ambiguous) name(s), (Colon, Monadic name(s)) EnglishNames=: 0 : 0 V V = Equal EQ XNor : SelfClassify V V < LessThan LT : Box Enclose V V <. LesserOf Min Inf : Floor V V <: LessOrEqual LessThanOrEqual LE : Decrement Previous V V > LargerThan GT : Open Unbox Disclose V V >. LargerOf Max Sup : Ceiling V V >: LargerOrEqual GE : Increment Next N _ Infinity N _. Indeterminate V _: InfinityVerb V V + Plus : Conjugate V V +. Or GCD : RealImaginary V V +: NotOr Nor : Double V V * Times : Signum Sign V V *. And LCM : LengthAngle V V *: NotAnd Nand : Square V V - Minus : Negate V V -. Less RemoveItems : Not Complement V V -: Match : Halve V V % Divide DividedBy : Reciprocal V V %. MatrixDivide : MatrixInverse V V %: Root : SquareRoot Sqrt V V ^ ToPower : Exp Exponent Exponential V V ^. Logarithm Log : NaturalLogarithm NaturalLog C ^: Power For V V $ Shape ReshapeItems : ShapeOf V V $. SparseAxes : Sparse V $: SelfReference Recursion A E ~ Evoke Reflexive Reflex Passive Swap . V ~. : Nub UniqueItems V V ~: NotEqual NE XOr : NubSieve UniqueSieve V V | Residue : Magnitude V V |. Rotate RotateLeft : Reverse V V |: AxisTranspose ReorderAxes : Transpose Trans C . DotProduct Determinant C .. Even C .: Odd C : MonadDyad ExplicitDefinition Explicit C :. Obverse C :: Adverse V V , Append : Ravel Enfile V V ,. Stitch : RavelItems EnfileItems V V ,: Laminate : Itemize V V ; Link : Raze C ;. Cut V V ;: FSM SequentialMachine : Words JWords V V # Copy : Tally Count V V #. Base : Base2 BaseTwo FromBase2 V V #: Antibase : Antibase2 AntibaseTwo ToBase2 V V ! Combinations OutOf CombOutOf : Factorial C !. Customize Fit C !: Foreign A A / Table Insert A A /. Key Oblique Diag V V /: SortUp : GradeUp A A \ Prefix Infix A A \. Suffix Outfix V V \: SortDown : GradeDown V V [ Left : SameL V [: Cap V V ] Right : Same Right1 V V { From : Catalogue V V {. Take : Head First . V {: : Tail Last V V {:: Fetch : Map A A } Mask ItemAmend Amend V V }. Drop : Behead . V }: : Curtail C " Rank V V ". Numbers : Do V V ": Format : DefaultFormat C ` Tie C `: EvokeGerund C @ Atop On C @. Agenda C @: At C & Compose Bond Curry PowerBond With C &. Dual Under C &.: UnderInfinite C &: Appose V V ? Deal : Roll Random V V ?. DealFixed : RollFixed RandomFixed N a. Alphabet N a: Ace Null V V A. Anagram : AnagramIndex A A b. Basic Boolean V V C. Permute : DirectCycle CycleDirect PermForm C d. Derivative0 C D. Derivative C D: SecantSlope V V e. In MemberIn : RazeIn V V E. MemberOfInterval WindowedMatch A f. Fix C H. Hypergeometric V V i. IndexOf : Integers V V i: IndexOfLast : Steps IntegerRange V V I. IntervalIndex : Indices V V j. Complex : Imaginary TimesJ V V L. LevelOf Depth C L: LevelAt V V o. CircleFunction Circular : PiTimes V V p. Polynomial : Roots V V p.. PolyIntegral : PolyDeriv V V p: PrimeInfo : Primes V V q: PrimeExponents PrimeExps : PrimeFactors V V r. Polar : Angle V V s: SymbolInfo : Symbol C S: Spread A t. TaylorCoefficient AssignTaylor A t: WeightedTaylor C T. TaylorApproximation V u: Unicode : UnicodeConvert V x: ExtendedPrecision Exact : NumDenom Rat V _9: NegNine V _8: NegEight V _7: NegSeven V _6: NegSix V _5: NegFive V _4: NegFour V _3: NegThree V _2: NegTwo V _1: NegOne V 0: Zero V 1: One V 2: Two V 3: Three V 4: Four V 5: Five V 6: Six V 7: Seven V 8: Eight V 9: Nine V '-@_:' NegInfinityVerb N '''''' Empty . V '#@$' RankOf V V '+/' PlusTable : PlusIns Sum Sigma C '&.>' Each V V '+/\' RunningSumTable : RunningSums RunSums V V '*/' TimesTable ProductTable : TimesIns Product PI V V '#&.>' CopyEach : CountEach . V '+/%#' : Average Mean V . '+/ .*' InnerProduct DotProduct : A 'L:0' Leaf V . '#^:_1' Expand ) NomsFrancais=: 0 : 0 ) NombresEspanoles=: 0 : 0 ) DeutscheNamen=: 0 : 0 ) RusskiImenyi=: 0 : 0 ) NB. --------------------------------------------------------- ALIASES=: EnglishNames NB. ALIASES=: TestSample NB. Utility from 'system\packages\misc\fndef.ijs' NB. *stoa v argument script NB. Converts any character vector to an array using NB. the last item as 'fret'. The characteristic use - from NB. a string to array - gives the name stoa stoa =: 3 : 0 > < ;._2 y ) NB. --------------------------------------------------------- NB. Establishes globals required for translation gendefs=: 3 : 0 NB. Separates table rows, tokenizes (boxing each symbol or name) nn1=: ([: (<@;:)"1 stoa) y NB. Groups between colons: usage(s) and symbol and dyadic name(s) : monadic nn2=: ((<;._1)@ ((<,':')&,)) each nn1 NB. Finds MonadDyad in leading group of some line nn2i=: I. , > (+./"1@ (>@ ((< 'MonadDyad')&=@ (>@ }.))))each nn2 NB. Inserts lost Colon verb after first token (C) nn3=: ((({. , ((< ':')&[) , }.)each@ {.)each nn2i{ nn2) nn2i } nn2 NB. Finds number of usage types leading each line nn3i=: > ((+/@ (((<@ ,)"0 'NVAC.E')&(e.~)@ (2&{.)))each@ {.)each nn3 NB. Re-arranges items grouped in boxes to show: NB. dyadic name(s), monadic (if distinguished), NB. graphic symbol, usages nn4=: nn3i (([ (}.@}.each) 1&{.) , (1: }. ]) , ([ ({.@}.each) 1&{.) , ( ([ {.each 1&{.)))each nn3 NB. Trims quotes from composites (idioms) nn4i=: I. , > ((, < '''''')&=@(2&{.each@ (_1&|.each@(>@(_2&{)))))each nn4 nn5=: (((_2&}.) , (<@ (".each@ (>@ (_2&{)))) , (_1&{)) each nn4i{ nn4) nn4i } nn4 NB. Collects non-verbs, dyads, monads (inserting Caps for "illegal" uses), NB. expanding to a separate item for each name LIT =: > (,each)/"2 (1 2 0 3&{"1 each@ (((<<'') &[) ,"1 each 0&{"1 (,"0 1 each"1) (1&{"1) ,.each ( {.each@ (2&{"1)))) > (3= > #each nn5)# nn5 LIT2=: > (,each)/"2 (1 0 2 3&{"1 each@ (((<<'[:')&[) ,"1 each 0&{"1 (,"0 1 each ) (2&{"1) , each ( {.each@ (3&{"1)))) > (4= > #each nn5)# nn5 LIT1=: > (,each)/"2 (1 2 0 3&{"1 each@ (((<<'[:')&[) ,"1 each 1&{"1 (,"0 1 each ) (2&{"1) , each (_1&{.each@ (3&{"1)))) > (4= > #each nn5)# nn5 ) NB. --------------------------------------------------------- NB. Incorporates use-flags into names as constant visual reminders of syntactic function attachflags=: 3 : 0 LIT=: ((0&{ ,each 3&{) , 1&}.)"1 LIT LIT1=: ((0&{ ,each 3&{) , 1&}.)"1 LIT1 LIT2=: ((0&{ ,each 3&{) , 1&}.)"1 LIT2 ) NB. Activate if desired NB. attachflags '' NB. optional NB. Constructs global translation tables gendefs ALIASES NB. Prefix/Remove NB. on next three lines to choose lowercase/CamelCase form NB. LIT =: (tolower each@ {."1 , }."1)"1 LIT NB. LIT1 =: (tolower each@ {."1 , }."1)"1 LIT1 NB. LIT2 =: (tolower each@ {."1 , }."1)"1 LIT2 NB. --------------------------------------------------------- NB. Remove/Prefix NB. on next three lines to activate tracking of each verb result NB. LIT =: (((< , 'V')&[ = 3&{"1) LIT) ((((< '(')&[ ,each 1&{ ,each (< ') T')&[)"1@ ([ # ])) ` (<@ ((a:&[@ [) ; 1&[@ ])) ` #) } LIT NB. LIT1 =: (((< , 'V')&[ = 3&{"1) LIT1) ((((< '(')&[ ,each 1&{ ,each (< ') T')&[)"1@ ([ # ])) ` (<@ ((a:&[@ [) ; 1&[@ ])) ` #) } LIT1 NB. LIT2 =: (((< , 'V')&[ = 3&{"1) LIT2) ((((< '(')&[ ,each 2&{ ,each (< ') T')&[)"1@ ([ # ])) ` (<@ ((a:&[@ [) ; 2&[@ ])) ` #) } LIT2 Track=: verb define NB. Passes argument y while: resetting tracking array Tr, or prepending (part of) y with x as label Tr_base_=: 0 3$ <'' y : Tr_base_=: (x; (((5 50&<.@ (_2&{.@ (1 1&,@ $))) {. ]) > ;._2 (5!:5 <'y'), 10{ a.); ($ y)), Tr_base_ y ) Track 99 NB. Finds semi-global context of current result--poorly informative in long expressions TrCont =: 1 : 0 NB. Choose to label with first token only--or--whole expression: NB. (> (0: { ;:@ }.) {. 13!:18 '') Track u y NB. (}: > ,each/ (,&' ')each ((<, 'T')&~: # ]) ;: }. {. 13!:18 '') Track u y : NB. Choose to label with first token only--or--whole expression: NB. (> (1: { ;:@ }.) {. 13!:18 '') Track x u y NB. (}: > ,each/ (,&' ')each ((<, 'T')&~: # ]) ;: }. {. 13!:18 '') Track x u y ) NB. Displays box array without primary horizontal separators nobar=: (((1&|.@ (_1 0&,@ (((9{ 9!:6 '')&=@ ({."1))# i.@ #))) {"2 ])@ ":) NB. --------------------------------------------------------- NB. Activates name definitions, unprotected (x) and protected (y) definealpha =: 4 : 0 0 0$". each (0{"1 x),"1 each (< ' =: '),"1 each (1{"1 x) 0 0$". each (0{"1 y),"1 each (< ' =: '),"1 each (1{"1 y),"1 each (< ' : '),"1 each (2{"1 y) ) NB. Sets up all verb names LIT definealpha LIT1, LIT2 NB. Defines protections not amenable to tacit format (translate for other language) PowerBond=: 2 : 0 [: : x u&v y ) Compose=: Bond=: Curry=: 2 : 0 u&v y : [: ) NB. --------------------------------------------------------- NB. Lists equivalent graphics ("unprotected")--in same order, alphabetised, or by usage genalias=: 3 : 0 ALIAS =: (0 1 3{"1 LIT), (0 1 3{"1 LIT1), 0 2 3{"1 LIT2 ALIASA=: ((0&{"1) ,"0 1 (1&{"1) ,"0 (2&{"1)) ((,@: (/:@: (0&{"1))) { ]) ALIAS ALIASU=: ((0&{"1) ,"0 1 (1&{"1) ,"0 (2&{"1)) ((,@: (/:@: (2&{"1))) { ]) ALIAS ) genalias '' NB. Displays name list y neatly (unboxed columns) incols=: (>@ ((,"1 each/)/@ ((>each@: (<"1@ |:)) ,"1 each (<' ')&[))) "0 2 NB. Displays y in two groups of boxed columns twocols=: (nobar@ (,./@ (":@ (>@ ((<.@ (%&_2@ #)) <\ ]))))) NB. --------------------------------------------------------- NB. Converts a script from alpha to primitive graphic form NB. The monadic form converts a noun script to primitives. NB. The dyadic form writes the file named in the left argument NB. to the file named in the right argument after conversion NB. of the script to primitives. toprimitives =: 3 : 0 tp =. ;: y stp =. $tp tp =. , tp tpi =. I. tp e. {."1 ALIAS tpii =. (0{"1 ALIAS) i. tpi{ tp NB. > ,&.>/ "1 gg =: stp$ (tpii{ ALIAS) tpi } tp hh =: (;:^:_1) "1 gg =: stp$ (tpii{ _2{"1 ALIAS) tpi } tp : (((toprimitives 'm' fread x),.CR),.LF) fwrite y ) NB. Loads an alpha-primitives J script in decoded form loada =: 3 : 0 y toprimitives jpath '~temp/zzzzzzz.ijs' 0!:000 < jpath '~temp/zzzzzzz.ijs' ferase jpath '~temp/zzzzzzz.ijs' ) NB. Loads and displays loadad =: 3 : 0 y toprimitives jpath '~temp/zzzzzzz.ijs' 0!:001 < jpath '~temp/zzzzzzz.ijs' ferase jpath '~temp/zzzzzzz.ijs' ) NB. ---------------------------------------------------------