[[DiscoveringApl|Discovering APL]] « [[../WhyVectors|Why Vectors?]] « [[../ShockingBrevity|A Shocking Brevity]] « = Some APL Examples = Here is an APL program to calculate the average (arithmetic mean) of a list of numbers. It is written in D, the ‘direct’ form of Dyalog APL. {{{ {(+/ω)÷ρω} }}} It is unnamed: the enclosing braces mark it as a function definition. It can be assigned a name for use later, or used anonymously in a more complex expression. The {{{ω}}} refers to the argument of the function, a list (or 1-dimensional array) of numbers. The {{{ρ}}} denotes the shape function, which returns here the length of (number of elements in) the argument {{{ω}}}. The divide symbol {{{÷}}} has its usual meaning. The parenthesised {{{+/ω}}} denotes the sum of all the elements of {{{ω}}}. The {{{/}}} operator combines with the {{{+}}} function: the {{{/}}} fixes the {{{+}}} function between each element of {{{ω}}}, so that {{{ +/ 1 2 3 4 5 6 21 }}} is the same as {{{ 1+2+3+4+5+6 21 }}} Operators like {{{/}}} can be used to derive new functions not only from primitive functions like {{{+}}}, but also from defined functions. For example {{{ {α,', ',ω}/ }}} will transform a list of strings representing words into a comma-separated list: {{{ {α,', ',ω}/'cow' 'sheep' 'cat' 'dog' cow, sheep, cat, dog }}} So back to our mean example. {{{(+/ω)}}} gives the sum of the list, which is then divided by {{{ρω}}}, the number of its elements. {{{ {(+/ω)÷ρω} 3 4.5 7 21 8.875 }}} == The same program in J == In J’s tacit definition no braces are needed to mark the definition of a function: primitive functions just combine in a way that enables us to omit any reference to the function arguments — hence tacit. Here is the same calculation written in J: {{{ (+/%#) 3 4.5 7 21 8.875 }}} In J’s terminology, functions are called verbs and operators adverbs. So: the verb # gives the length of the argument. Division is marked by % instead of ÷. The sum verb is again marked by +/: the verb + is modified by the adverb /. The adverb \ can be used to modify the +/%# verb to produce a moving average. {{{ 2 (+/%#)\ 3 4.5 7 21 3.75 5.75 14 }}} or, more verbosely {{{ ave =: +/%# ave 3 4.5 7 21 8.875 mave =: ave\ 2 mave 3 4.5 7 21 3.75 5.75 14 }}} The J wiki (see http://www.jsoftware.com/jwiki/Essays) contains a selection of essays in which you can see similarly succinct solutions to a range of problems. » [[../AplAndTypography| APL & Typography]] ---- CategoryAboutApl