Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

APL syntax and symbols

From Wikipedia, the free encyclopedia
Set of rules defining correctly structured programs
This article mayrequirecleanup to meet Wikipedia'squality standards. The specific problem is:This article has non-standard layout and formatting. Please helpimprove this article if you can.(October 2015) (Learn how and when to remove this message)
This article containsAPLsource code. Without properrendering support, you may seequestion marks, boxes, or other symbols instead ofAPL symbols.

The programming languageAPL is distinctive in beingsymbolic rather thanlexical: its primitives are denoted bysymbols, not words. These symbols were originally devised as amathematical notation to describe algorithms.[1] APL programmers often assign informal names when discussing functions and operators (for example, "product" for ×/) but the core functions and operators provided by the language are denoted by non-textual symbols.

Monadic and dyadic functions

[edit]

Most symbols denotefunctions oroperators. Amonadic function takes as its argument the result of evaluating everything to its right. (Moderated in the usual way by parentheses.) Adyadic function has another argument, the first item of data on its left. Many symbols denote both monadic and dyadic functions, interpreted according to use. For example, ⌊3.2 gives 3, the largest integer not above the argument, and 3⌊2 gives 2, the lower of the two arguments.

Functions and operators

[edit]

APL uses the termoperator inHeaviside’s sense as a moderator of a function as opposed to some other programming language's use of the same term as something that operates on data, ref.relational operator andoperators generally. Other programming languages also sometimes use this term interchangeably withfunction, however both terms are used in APL more precisely.[2][3][4][5][6] Early definitions of APL symbols were very specific about how symbols were categorized.[7] For example, the operatorreduce is denoted by a forward slash and reduces an array along one axis by interposing its functionoperand. An example ofreduce:

      ×/2 3 424
<<Equivalent results in APL >>
<<Reduce operator/ used at left
      2×3×424

In the above case, thereduce orslash operatormoderates themultiply function. The expression×/2 3 4 evaluates to a scalar (1 element only) result throughreducing an array by multiplication. The above case is simplified, imagine multiplying (adding, subtracting or dividing) more than just a few numbers together. (From a vector,×/ returns the product of all its elements.)


      1 0 1\45 6745 0 67
<<Opposite results in APL >>
<<Expand dyadic function\ used at left
Replicate dyadic function/ used at right >>
      1 0 1/45 0 6745 67

The abovedyadic functions examples [left and right examples] (using the same/ symbol, right example) demonstrate howBoolean values (0s and 1s) can be used as left arguments for the\ expand and/ replicatefunctions to produce exactly opposite results. On the left side, the2-elementvector {45 67} isexpanded where Boolean 0s occur to result in a3-element vector {45 0 67} — note how APL inserted a 0 into the vector. Conversely, the exact opposite occurs on the right side — where a 3-element vector becomes just 2-elements; Boolean 0sdelete items using the dyadic/ slash function. APL symbols also operate onlists (vector) of items using data types other than just numeric, for example a 2-element vector of character strings {"Apples" "Oranges"} could be substituted for numeric vector {45 67} above.

Syntax rules

[edit]

In APL theprecedence hierarchy for functions or operators is strictly positional: expressions are evaluated right-to-left. APL does not follow the usualoperator precedence of other programming languages; for example,× does not bind its operands any more "tightly" than+. Instead of operator precedence, APL defines a notion ofscope.

Thescope of afunction determines itsarguments. Functions havelong right scope: that is, they take as right arguments everything to their right. A dyadic function hasshort left scope: it takes as its left arguments the first piece of data to its left. For example, (leftmost column below is actualprogram code from an APLuser session, indented = actualuser input, not-indented = result returned byAPL interpreter):

1÷23×4-5¯0.33333333331÷23ׯ1¯0.33333333331÷2¯3¯0.33333333331÷¯3¯0.3333333333

<< First note there are no parentheses and
APL is going to execute from right-to-left.
Step 1{of topmost APL code entered at left}) 4-5 = -1.

Step 2) 3 times -1 = -3.
Step 3) Take thefloor orlower of 2 and -3 = -3.
Step 4) Divide 1 by -3 = -0.3333333333 = final result.


An operator may have function or dataoperands and evaluate to a dyadic or monadic function. Operators have long left scope. An operator takes as its left operand the longest function to its left. For example:

     ∘.=/⍳¨3 3 1 0 0 0 1 0 0 0 1

APLatomic or piecemeal sub-analysis (full explanation):
Beginning rightmost: ⍳¨3 3 produces a 2-element nested APL vector { {1 2 3} {1 2 3} } where each element is itself a vector {1 2 3}.Iota ⍳3 by itself would produce {1 2 3}.

Thediaeresis ¨ or mini double-dot meansrepeat orover each orperform each separately soiota repeats (in human i.e., reversed terms, the APL interpreter reads 3 3 over each use iota), concisely:iota for each 3.

The left operand for theover-each operator¨ is theindex ⍳ function. Thederived function⍳¨ is used monadically and takes as its right operand the vector3 3. The left scope ofeach is terminated by thereduce operator, denoted by the forwardslash. Its left operand is the function expression to its left: theouter product of theequals function. The result of ∘.=/ is a monadic function. With a function's usual long right scope, it takes as its right argument the result of ⍳¨3 3. Thus

(⍳3)(⍳3)1 2 3  1 2 3(⍳3)∘.=⍳31 0 00 1 00 0 1⍳¨3 31 2 3  1 2 3∘.=/⍳¨3 3 1 0 0 0 1 0 0 0 1


Equivalent results in APL:(⍳3)(⍳3) and⍳¨3 3 << Rightmost expression ismore concise.

The matrix of 1s and 0s similarly produced by∘.=/⍳¨3 3 and(⍳3)∘.=⍳3 is called anidentity matrix.

Identity matrices are useful in solvingmatrix determinants, groups oflinear equations andmultiple regression.


im∘.=⍨∘im3100010001

Some APL interpreters support thecompose operator ∘ and thecommute operator ⍨. The former∘ glues functions together so thatfoo∘bar, for example, could be a hypothetical function that applies defined functionfoo to the result of defined functionbar; foo and bar can representany existing function. In cases where a dyadic function is moderated bycommute and then used monadically, its right argument is taken as its left argument as well. Thus, aderived orcomposed function (namedim at left) is used in the APL user session to return a 9-element identity matrix using its rightargument,parameter or operand = 3.


Letters"ABCDE"LettersABCDELetters5FindIt"CABS"FindItCABSFindIt4LettersFindIt3126

Example using APL toindex ⍳ orfind (or not find) elements in a character vector:

First, variableLetters is assigned a vector of 5-elements, in this case - letters of the alphabet.

Theshape ⍴ or character vector-length ofLetters is 5.

VariableFindIt is assigned what tosearch for inLetters and its length is 4 characters.

1 2 3 4 5 << vector positions or index #'s inLetters
ABCDE

At left, dyadic functioniota searches through its left argument(Letters) for the search string (iota's right argument, FindIt).

Iota finds letter "C" at position 3 in Letters, it finds "A" at position 1, and "B" at position 2.Iota doesnot find letter "S"

anywhere in variable Letters so it returns the number 6 which is1 greater than the length of Letters.Iota found letters

"CAB" (3 1 2).Iota correctly didnot find "S" (6).

Monadic functions

[edit]
Name(s)NotationMeaningUnicode code point
Roll?BOne integer selected randomly from the firstB integersU+003F?QUESTION MARK
Ceiling⌈BLeast integer greater than or equal toBU+2308LEFT CEILING
Floor⌊BGreatest integer less than or equal toBU+230ALEFT FLOOR
Shape,Rho⍴BNumber of components in each dimension ofBU+2374APL FUNCTIONAL SYMBOL RHO
Not,Tilde∼BLogical: ∼1 is 0, ∼0 is 1U+223CTILDE OPERATOR
Absolute value∣BMagnitude ofBU+2223DIVIDES
Index generator,Iota⍳BVector of the firstB integersU+2373APL FUNCTIONAL SYMBOL IOTA
Exponential⋆Be to theB powerU+22C6STAR OPERATOR
Negation−BChanges sign ofBU+2212MINUS SIGN
Conjugate+BThe complex conjugate ofB (real numbers are returned unchanged)U+002B+PLUS SIGN
Signum×B¯1 ifB<0; 0 ifB=0; 1 ifB>0U+00D7×MULTIPLICATION SIGN
Reciprocal÷B1 divided byBU+00F7÷DIVISION SIGN
Ravel, Catenate, Laminate,BReshapesB into a vectorU+002C,COMMA
Matrix inverse, Monadic Quad Divide⌹BInverse of matrixBU+2339APL FUNCTIONAL SYMBOL QUAD DIVIDE
Pi times○BMultiply by πU+25CBWHITE CIRCLE
Logarithm⍟BNatural logarithm ofBU+235FAPL FUNCTIONAL SYMBOL CIRCLE STAR
Reversal⌽BReverse elements ofB along last axisU+233DAPL FUNCTIONAL SYMBOL CIRCLE STILE
Reversal⊖BReverse elements ofB along first axisU+2296CIRCLED MINUS
Grade up⍋BIndices ofB which will arrangeB in ascending orderU+234BAPL FUNCTIONAL SYMBOL DELTA STILE
Grade down⍒BIndices ofB which will arrangeB in descending orderU+2352APL FUNCTIONAL SYMBOL DEL STILE
Execute⍎BExecute anAPL expressionU+234EAPL FUNCTIONAL SYMBOL DOWN TACK JOT
Monadic format⍕BA character representation ofBU+2355APL FUNCTIONAL SYMBOL UP TACK JOT
Monadictranspose⍉BReverse the axes ofBU+2349APL FUNCTIONAL SYMBOL CIRCLE BACKSLASH
Factorial!BProduct of integers 1 toBU+0021!EXCLAMATION MARK
Depth≡BNesting depth: 1 for un-nested arrayU+2261IDENTICAL TO
Table⍪BMakesB into a table, a 2-dimensional array.U+236AAPL FUNCTIONAL SYMBOL COMMA BAR

Dyadic functions

[edit]
Name(s)NotationMeaningUnicode
code point
AddA+BSum ofA andBU+002B+PLUS SIGN
SubtractA−BA minusBU+2212MINUS SIGN
MultiplyA×BA multiplied byBU+00D7×MULTIPLICATION SIGN
DivideA÷BA divided byBU+00F7÷DIVISION SIGN
ExponentiationA⋆BA raised to theB powerU+22C6STAR OPERATOR
CircleA○BTrigonometric functions ofB selected byA
A=1: sin(B)A=5: sinh(B)A=2: cos(B)A=6: cosh(B)A=3: tan(B)A=7: tanh(B)

Negatives produce the inverse of the respective functions

U+25CBWHITE CIRCLE
DealA?BA distinct integers selected randomly from the firstB integers (without replacement)U+003F?QUESTION MARK
Membership, EpsilonA∈B1 for elements ofA present inB; 0 where not.U+2208ELEMENT OF
Find, Epsilon UnderbarA⍷B1 for starting point of multi-item arrayA present inB; 0 where not.U+2377APL FUNCTIONAL SYMBOL EPSILON UNDERBAR
Maximum, CeilingA⌈BThe greater value ofA orBU+2308LEFT CEILING
Minimum, FloorA⌊BThe smaller value ofA orBU+230ALEFT FLOOR
Reshape, DyadicRhoA⍴BArray of shapeA with dataBU+2374APL FUNCTIONAL SYMBOL RHO
TakeA↑BSelect the first (or last)A elements ofB according to ×AU+2191UPWARDS ARROW
DropA↓BRemove the first (or last)A elements ofB according to ×AU+2193DOWNWARDS ARROW
DecodeA⊥BValue of a polynomial whose coefficients areB atAU+22A5UP TACK
EncodeA⊤BBase-A representation of the value ofBU+22A4DOWN TACK
ResidueA∣BB moduloA;A dividesBU+2223DIVIDES
CatenationA,BElements ofB appended to the elements ofAU+002C,COMMA
Expansion, Dyadic BackslashA\BInsert zeros (or blanks) inB corresponding to zeros inAU+005C\REVERSE SOLIDUS
Compression, Dyadic SlashA/BSelect elements inB corresponding to ones inAU+002F/SOLIDUS
Index of, DyadicIotaA⍳BThe location (index) ofB inA;1+⍴A if not foundU+2373APL FUNCTIONAL SYMBOL IOTA
Matrix divide, Dyadic Quad DivideA⌹BSolution tosystem of linear equations,multiple regressionAx =BU+2339APL FUNCTIONAL SYMBOL QUAD DIVIDE
RotationA⌽BThe elements ofB are rotatedA positionsU+233DAPL FUNCTIONAL SYMBOL CIRCLE STILE
RotationA⊖BThe elements ofB are rotatedA positions along the first axisU+2296CIRCLED MINUS
LogarithmA⍟BLogarithm ofB to baseAU+235FAPL FUNCTIONAL SYMBOL CIRCLE STAR
Dyadic formatA⍕BFormatB into a character matrix according toAU+2355APL FUNCTIONAL SYMBOL UP TACK JOT
General transposeA⍉BThe axes ofB are ordered byAU+2349APL FUNCTIONAL SYMBOL CIRCLE BACKSLASH
CombinationsA!BNumber of combinations ofB takenA at a timeU+0021!EXCLAMATION MARK
Diaeresis, Dieresis, Double-DotA¨BOver each, or perform each separately;B = on these;A = operation to perform or using (e.g., iota)U+00A8¨DIAERESIS
Less thanA<BComparison: 1 if true, 0 if falseU+003C<LESS-THAN SIGN
Less than or equalA≤BComparison: 1 if true, 0 if falseU+2264LESS-THAN OR EQUAL TO
EqualA=BComparison: 1 if true, 0 if falseU+003D=EQUALS SIGN
Greater than or equalA≥BComparison: 1 if true, 0 if falseU+2265GREATER-THAN OR EQUAL TO
Greater thanA>BComparison: 1 if true, 0 if falseU+003E>GREATER-THAN SIGN
Not equalA≠BComparison: 1 if true, 0 if falseU+2260NOT EQUAL TO
OrA∨BBoolean Logic:0 (False) ifbothA andB =0, 1 otherwise. Alt:1 (True) ifAorB =1 (True)U+2228LOGICAL OR
AndA∧BBoolean Logic:1 (True) ifbothAandB =1, 0 (False) otherwiseU+2227LOGICAL AND
NorA⍱BBoolean Logic: 1 if bothA andB are 0, otherwise 0. Alt: ~∨ = not OrU+2371APL FUNCTIONAL SYMBOL DOWN CARET TILDE
NandA⍲BBoolean Logic: 0 if bothA andB are 1, otherwise 1. Alt: ~∧ = not AndU+2372APL FUNCTIONAL SYMBOL UP CARET TILDE
LeftA⊣BAU+22A3LEFT TACK
RightA⊢BBU+22A2RIGHT TACK
MatchA≡B1 ifA matchesB exactly with respect to value, shape, and nesting; otherwise 0.U+2261IDENTICAL TO
LaminateA⍪BConcatenate along first axisU+236AAPL FUNCTIONAL SYMBOL COMMA BAR

Operators and axis indicator

[edit]
Name(s)SymbolExampleMeaning (of example)Unicode code point sequence
Reduce (last axis), Slash/+/BSum acrossBU+002F/SOLIDUS
Reduce (first axis)+⌿BSum downBU+233FAPL FUNCTIONAL SYMBOL SLASH BAR
Scan (last axis), Backslash\+\BRunning sum acrossBU+005C\REVERSE SOLIDUS
Scan (first axis)+⍀BRunning sum downBU+2340APL FUNCTIONAL SYMBOL BACKSLASH BAR
Inner product.A+.×BMatrix product ofA andBU+002E.FULL STOP
Outer product∘.A∘.×BOuter product ofA andBU+2218RING OPERATOR,U+002E.FULL STOP

Notes: The reduce and scan operators expect a dyadic function on their left, forming a monadic composite function applied to the vector on its right.

The product operator "." expects a dyadic function on both its left and right, forming a dyadic composite function applied to the vectors on its left and right. If the function to the left of the dot is "∘" (signifying null) then the composite function is an outer product, otherwise it is an inner product. An inner product intended for conventional matrix multiplication uses the + and × functions, replacing these with other dyadic functions can result in useful alternative operations.

Some functions can be followed by an axis indicator in (square) brackets, i.e., this appears between a function and an array and should not be confused with array subscripts written after an array. For example, given the ⌽ (reversal) function and a two-dimensional array, the function by default operates along the last axis but this can be changed using an axis indicator:

A43⍴⍳12A123456789101112A321654987121110[1]A101112789456123⊖⌽A121110987654321A147102581136912


4 rows by 3 cols matrix created, usingrho ⍴ andiota ⍳. The 4 x 3 matrix is then stored in avariable namedA.

A is now reflected or flipped along its vertical axis assymbol ⌽ visually indicates.

A is now reflected using the[1] axis indicator orfirst dimension modifier. The result is that variable A has been reflected across the horizontal axis, instead of vertically.

A is now reflected bothvertically ⊖ andhorizontally ⌽.

A is⍉ transposed to a 3 row by 4 col matrix such that rows-cols become exchanged, assymbol ⍉ visually portrays. Compare the result here to the original matrix stored in A, topmost matrix. These types of data transformations are useful intime series analysis andspatial coordinates, just two examples,more exist.


As a particular case, if the dyadiccatenate"," function is followed by anaxis indicator (oraxis modifier to a symbol/function), it can be used to laminate (interpose) two arrays depending on whether the axis indicator is less than or greater than theindex origin[8] (index origin = 1 in illustration below):

B1234C5678B,C12345678B,[0.5]C12345678B,[1.5]C15263748

At left, variable 'B' is first assigned a vector of 4 consecutive integers (e.g.,⍳4).
VarC is then assigned 4 more consecutive integers (such as4+⍳4).
'B' andC are thenconcatenated orraveled together for illustration purposes,
resulting in a single vector (⍳8).In the particular case at left, if the dyadiccatenate "," function is followed by anaxis indicator ([0.5] which isless than 1), it can be used tolaminate (interpose) two arrays (vectors in this case) depending on whether the axis indicator is less than or greater than the index origin(1). Thefirst result (ofB,[0.5]C) is a 2 row by 4 column matrix, vertically joining 'B' andC row-wise. Thesecond result (ofB,[1.5]C which isgreater than 1) is a 4 row by 2 column matrix.

Nested arrays

[edit]

Arrays are structures which have elements grouped linearly asvectors or in table form asmatrices—and higher dimensions (3D or cubed,4D or cubed over time, etc.). Arrays containing both characters and numbers are termedmixed arrays.[9] Array structures containing elements which are also arrays are callednested arrays.[10]

Creating a nested array
User session with APL interpreterExplanation
X45⍴⍳20X1234567891011121314151617181920X[2;2]7⎕IO1X[1;1]1


X set = to matrix with 4 rows by 5 columns, consisting of 20 consecutive integers.

ElementX[2;2] in row 2 - column 2 currently is an integer = 7.

Initialindex origin⎕IO value =1.

Thus, the first element in matrix X orX[1;1] = 1.

X[2;2]"Text"X[3;4](22⍴⍳4)X123456Text89101112131215341617181920
Element in X[row 2; col 2] is changed (from 7) to anested vector "Text" using theenclose ⊂ function.


Element in X[row 3; col 4], formerly integer 14, now becomes a minienclosed or ⊂ nested 2x2 matrix of 4 consecutive integers.

SinceX containsnumbers,text andnested elements, it is both amixed and anested array.

Visual representation of thenested array

Flow control

[edit]

Auser may define customfunctions which, like variables, are identified byname rather than by a non-textual symbol. Thefunction header defines whether a custom function is niladic (no arguments), monadic (one right argument) or dyadic (left and right arguments), the local name of theresult (to the left of the← assign arrow), and whether it has any local variables (each separated by semicolon ';').

User functions
Niladic function PI or π(pi)Monadic function CIRCLEAREADyadic function SEGMENTAREA, with local variables
RESULTPIRESULT1
AREACIRCLEAREARADIUSAREAPI×RADIUS2
AREADEGREESSEGMENTAREARADIUS;FRACTION;CAFRACTIONDEGREES÷360CACIRCLEAREARADIUSAREAFRACTION×CA

Whether functions with the same identifier but differentadicity are distinct is implementation-defined. If allowed, then a function CURVEAREA could be defined twice to replace both monadic CIRCLEAREA and dyadic SEGMENTAREA above, with the monadic or dyadic function being selected by the context in which it was referenced.

Custom dyadic functions may usually be applied to parameters with the same conventions as built-in functions, i.e., arrays should either have the same number of elements or one of them should have a single element which is extended. There are exceptions to this, for example a function to convert pre-decimal UK currency to dollars would expect to take a parameter with precisely three elements representing pounds, shillings and pence.[11]

Inside a program or a custom function, control may be conditionally transferred to a statement identified by a line number or explicit label; if the target is 0 (zero) this terminates the program or returns to a function's caller. The most common form uses the APL compression function, as in the template (condition)/target which has the effect of evaluating the condition to 0 (false) or 1 (true) and then using that to mask the target (if the condition is false it is ignored, if true it is left alone so control is transferred).

Hence function SEGMENTAREA may be modified to abort (just below), returning zero if the parameters (DEGREES and RADIUS below) are ofdifferent sign:

AREADEGREESSEGMENTAREARADIUS;FRACTION;CA;SIGN⍝ local variables denoted by semicolon(;)FRACTIONDEGREES÷360CACIRCLEAREARADIUS⍝ this APL code statement calls user function CIRCLEAREA, defined up above.SIGN(×DEGREES)≠×RADIUS⍝ << APL logic TEST/determine whether DEGREES and RADIUS do NOT (≠ used) have same SIGN 1-yes different(≠), 0-no(same sign)AREA0⍝ default value of AREA set = zeroSIGN/0⍝ branching(here, exiting) occurs when SIGN=1 while SIGN=0 does NOT branch to 0.  Branching to 0 exits function.AREAFRACTION×CA

The above function SEGMENTAREAworks as expected if the parameters arescalars or single-element arrays, butnot if they are multiple-elementarrays since the condition ends up being based on a single element of the SIGN array - on the other hand, the user function could be modified to correctly handle vectorized arguments. Operation can sometimes be unpredictable since APL defines that computers with vector-processing capabilitiesshould parallelise andmay reorder array operations as far as possible - thus,test and debuguser functions particularly if they will be used with vector or even matrix arguments. This affects not only explicit application of a custom function to arrays, but also its use anywhere that a dyadic function may reasonably be used such as in generation of a table of results:

90180270¯90∘.SEGMENTAREA1¯24000000000000

A more concise way and sometimes better way - to formulate a function is to avoid explicit transfers of control, instead using expressions which evaluate correctly in all or the expected conditions. Sometimes it is correct to let a function fail when one or bothinput arguments areincorrect - precisely to let user know that one or both arguments used were incorrect. The following is more concise than the above SEGMENTAREA function. The below importantlycorrectly handles vectorized arguments:

AREADEGREESSEGMENTAREARADIUS;FRACTION;CA;SIGNFRACTIONDEGREES÷360CACIRCLEAREARADIUSSIGN(×DEGREES)≠×RADIUSAREAFRACTION×CA×~SIGN⍝ this APL statement is more complex, as a one-liner - but it solves vectorized arguments: a tradeoff - complexity vs. branching90180270¯90∘.SEGMENTAREA1¯240.785398163012.56637061.57079633025.13274122.35619449037.69911180¯3.141592650

Avoiding explicit transfers of control also called branching, if not reviewed or carefully controlled - can promote use of excessively complexone liners, veritably "misunderstood and complex idioms" and a "write-only" style, which has done little to endear APL to influential commentators such asEdsger Dijkstra.[12]Conversely however APL idioms can be fun, educational and useful - if used with helpfulcomments ⍝, for example including source and intended meaning and function of the idiom(s). Here is anAPL idioms list, anIBM APL2 idioms list here[13] andFinnish APL idiom library here.

Miscellaneous

[edit]
Miscellaneous symbols
Name(s)SymbolExampleMeaning (of example)Unicode code point
High minus[14]¯¯3Denotes a negative numberU+00AF¯MACRON
Lamp, Comment⍝This is a commentEverything to the right of ⍝ denotes a commentU+235DAPL FUNCTIONAL SYMBOL UP SHOE JOT
RightArrow, Branch, GoTo→This_Label→This_Label sends APL execution to This_Label:U+2192RIGHTWARDS ARROW
Assign, LeftArrow, Set toB←AB←A sets values and shape of B to match AU+2190LEFTWARDS ARROW

Most APL implementations support a number of system variables and functions, usually preceded by the⎕ (quad) and/or")" (hook=close parenthesis) character. Note that the quad character is not the same as theUnicode missing character symbol. Particularly important and widely implemented is the ⎕IO (Index Origin) variable, since while the original IBM APL based its arrays on 1 some newer variants base them on zero:

User session with APL interpreterDescription
X12X123456789101112⎕IO1X[1]1

X set = to vector of 12 consecutive integers.

Initialindex origin⎕IO value =1. Thus, the first position in vector X orX[1] = 1 per vector of iota values {1 2 3 4 5 ...}.

⎕IO0X[1]2X[0]1
Index Origin⎕IO now changed to 0. Thus, the 'first index position' in vector X changes from 1 to 0. Consequently,X[1] then references or points to2 from {12 3 4 5 ...} andX[0] now references1.
⎕WA41226371072
Quad WA or⎕WA, another dynamicsystem variable, shows how much Work Area remainsunused or 41,226megabytes or about 41gigabytes of unusedadditional total free work area available for the APL workspace and program to process using. If this number gets low or approaches zero - the computer may need morerandom-access memory (RAM),hard disk drive space or some combination of the two to increasevirtual memory.
)VARSX
)VARS a system function in APL,[15])VARS shows user variable names existing in the current workspace.

There are also system functions available to users for saving the current workspace e.g.,)SAVE and terminating the APL environment, e.g.,)OFF - sometimes calledhook commands or functions due to the use of a leading right parenthesis or hook.[16] There is some standardization of these quad and hook functions.

Fonts

[edit]

The UnicodeBasic Multilingual Plane includes the APL symbols in theMiscellaneous Technical block,[17] which are thus usually rendered accurately from the larger Unicode fonts installed with most modern operating systems. These fonts are rarely designed by typographers familiar with APL glyphs. So, while accurate, the glyphs may look unfamiliar to APL programmers or be difficult to distinguish from one another.

Some Unicode fonts have been designed to display APL well: APLX Upright, APL385 Unicode, and SimPL.

Before Unicode, APL interpreters were supplied with fonts in which APL characters were mapped to less commonly used positions in the ASCII character sets, usually in the upper 128 code points. These mappings (and their national variations) were sometimes unique to each APL vendor's interpreter, which made the display of APL programs on the Web, in text files and manuals - frequently problematic.

APL2 keyboard function to symbol mapping

[edit]
APL2 Keyboard
APL2 Keyboard

Note the APL On/Off Key - topmost-rightmost key, just below. Also note the keyboard had some 55 unique (68 listed per tables above, including comparative symbols but several symbols appear inboth monadic and dyadic tables) APL symbol keys (55 APL functions (operators) are listed in IBM's 5110 APL Reference Manual), thus with the use of alt, shift and ctrl keys - it would theoretically have allowed a maximum of some59 (keys)*4 (with 2-key pressing)*3 (with tri-key pressing, e.g., ctrl-alt-del) or some 472 different maximum key combinations, approaching the 512EBCDIC character max (256 chars times 2 codes for each keys-combination). Again, in theory the keyboard pictured here would have allowed for about 472 different APL symbols/functions to be keyboard-input, actively used. In practice, early versions were only using somethingroughly equivalent to 55 APL special symbols (excluding letters, numbers, punctuation, etc. keys). Thus, early APL was then only using about 11% (55/472) of a symbolic language's at-that-time utilization potential, based on keyboard # keys limits, again excluding numbers, letters, punctuation, etc. In another sense keyboard symbols utilization was closer to 100%, highly efficient, since EBCDIC only allowed 256 distinct chars, andASCII only 128.

Solving puzzles

[edit]

APL has proved to be extremely useful in solving mathematical puzzles, several of which are described below.

Pascal's triangle

[edit]

TakePascal's triangle, which is a triangular array of numbers in which those at the ends of the rows are 1 and each of the other numbers is the sum of the nearest two numbers in the row just above it (the apex, 1, being at the top). The following is an APL one-liner function to visually depict Pascal's triangle:

Pascal{' '@(0=⊢)0,⍨¨a¨⌽∊¨0,¨¨a!¨a⌽⍳}⍝ Create a one-line user function called PascalPascal7⍝ Run function Pascal for seven rows and show the results below:1121331464151010516152015617213535217

Prime numbers, contra proof via factors

[edit]

Determine the number ofprime numbers (prime # is a natural numbergreater than 1 that has no positive divisors other than 1 and itself) up to some number N.Ken Iverson is credited with the following one-liner APL solution to the problem:

⎕CR'PrimeNumbers'⍝ Show APL user-function PrimeNumbersPrimesPrimeNumbersN⍝ Function takes one right arg N (e.g., show prime numbers for 1 ... int N)Primes(2=+0=(N)∘.|⍳N)/N⍝ The Ken Iverson one-linerPrimeNumbers100⍝ Show all prime numbers from 1 to 1002357111317192329313741434753596167717379838997PrimeNumbers10025⍝ There are twenty-five prime numbers in the range up to 100.

Examining the converse or opposite of a mathematical solution is frequently needed (integer factors of a number): Prove for the subset of integers from 1 through 15 that they arenon-prime by listing theirdecomposition factors. What are their non-one factors (#'s divisible by, except 1)?

⎕CR'ProveNonPrime'ZProveNonPrimeR⍝Show all factors of an integer R - except 1 and the number itself,⍝ i.e., prove Non-Prime. String 'prime' is returned for a Prime integer.Z(0=(R)|R)/R⍝ Determine all factors for integer R, store into ZZ(~(Z1,R))/Z⍝ Delete 1 and the number as factors for the number from Z.(0=⍴Z)/ProveNonPrimeIsPrime⍝ If result has zero shape, it has no other factors and is therefore primeZR,(" factors(except 1) "),(Z),⎕TCNL⍝ Show the number R, its factors(except 1,itself), and a new line char0⍝ Done with function if non-primeProveNonPrimeIsPrime:ZR,(" prime"),⎕TCNL⍝ function branches here if number was primeProveNonPrime¨15⍝ Prove non primes for each(¨) of the integers from 1 through 15 (iota 15)1prime2prime3prime4factors(except1)25prime6factors(except1)237prime8factors(except1)249factors(except1)310factors(except1)2511prime12factors(except1)234613prime14factors(except1)2715factors(except1)35

Fibonacci sequence

[edit]

Generate aFibonacci number sequence, where each subsequent number in the sequence is the sum of the prior two:

⎕CR'Fibonacci'⍝ Display function FibonacciFibonacciNumFibonacciNth;IOwas⍝ Funct header, funct name=Fibonacci, monadic funct with 1 right hand arg Nth;local var IOwas, and a returned num.⍝Generate a Fibonacci sequenced number where Nth is the position # of the Fibonacci number in the sequence.  << function descriptionIOwas⎕IO⎕IO0FibonacciNum01↓↑+.×/Nth/221110⎕IOIOwas⍝ In order for this function to work correctly ⎕IO must be set to zero.Fibonacci¨14⍝ This APL statement says: Generate the Fibonacci sequence over each(¨) integer number(iota or ⍳) for the integers 1..14.01123581321345589144233⍝ Generated sequence, i.e., the Fibonacci sequence of numbers generated by APL's interpreter.

Further reading

[edit]

See also

[edit]

References

[edit]
  1. ^Iverson, Kenneth E. (1962-01-01). "A programming language".Proceedings of the May 1-3, 1962, spring joint computer conference on - AIEE-IRE '62 (Spring). New York, NY, USA: ACM. pp. 345–351.doi:10.1145/1460833.1460872.S2CID 11777029.
  2. ^Baronet, Dan."Sharp APL Operators".archive.vector.org.uk. Vector - Journal of the British APL Association. Retrieved13 January 2015.
  3. ^MicroAPL."Primitive Operators".www.microapl.co.uk. MicroAPL. Retrieved13 January 2015.
  4. ^MicroAPL."Operators".www.microapl.co.uk. MicroAPL. Retrieved13 January 2015.
  5. ^Progopedia."APL".progopedia.com. Progopedia. Retrieved13 January 2015.
  6. ^Dyalog."D-functions and operators loosely grouped into categories".dfns.dyalog.com. Dyalog. Retrieved13 January 2015.
  7. ^IBM."IBM 5100 APL Reference Manual"(PDF).bitsavers.trailing-edge.com. IBM. Archived fromthe original(PDF) on 14 January 2015. Retrieved14 January 2015.
  8. ^Brown, Jim (1978)."In defense of index origin 0".ACM SIGAPL APL Quote Quad.9 (2): 7.doi:10.1145/586050.586053.S2CID 40187000.
  9. ^MicroAPL."APLX Language Manual"(PDF).www.microapl.co.uk. MicroAPL - Version 5 .0 June 2009. p. 22. Retrieved31 January 2015.
  10. ^Benkard, J. Philip (1992). "Nested arrays and operators: Some issues in depth".Proceedings of the international conference on APL - APL '92.ACM SIGAPL APL Quote Quad. Vol. 23, no. 1. pp. 7–21.doi:10.1145/144045.144065.ISBN 978-0897914772.S2CID 7760410.
  11. ^Berry, Paul"APL\360 Primer Student Text", IBM Research, Thomas J. Watson Research Center, 1969.
  12. ^"Treatise"(PDF).www.cs.utexas.edu. Retrieved2019-09-10.
  13. ^Cason, Stan (13 May 2006)."APL2 Idioms Library".www-01.ibm.com. IBM. Retrieved1 February 2015.
  14. ^APL's "high minus" applies to the single number that follows, while the monadic minus function changes the sign of the entire array to its right.
  15. ^"The Workspace - System Functions". Microapl.co.uk. p. (toward bottom of the web page). Retrieved2018-11-05.
  16. ^"APL language reference"(PDF). Retrieved2018-11-05.
  17. ^Unicode chart"Miscellaneous Technical (including APL)"(PDF).

External links

[edit]

Generic online tutorials

[edit]

Syntax rules

[edit]
Features
Implementations
Major
  • Dyalog APL
  • APL2 →APLX
  • SHARP APL
  • NARS → NARS2000°
Dialects
Community
Professional
associations
Organizations
Business
Education
People
Lists ofUnicode andLaTeX mathematical symbols
Lists ofUnicode symbols
General
Alphanumeric
Arrows andGeometric Shapes
Operators
Supplemental Math Operators
Miscellaneous
Typographical conventions and notations
Language
Letters
Notation
Meanings of symbols
Retrieved from "https://en.wikipedia.org/w/index.php?title=APL_syntax_and_symbols&oldid=1287784759"
Categories:
Hidden categories:

[8]ページ先頭

©2009-2025 Movatter.jp