Array-Oriented Programming

In most languages you process data one element at a time in a loop. In array-oriented programming the array is the basic value, and every operation applies to whole arrays at once. Instead of "for each item, add one", you write "add one to the array". The loop disappears, and often so does most of the code.

Think in Whole Arrays

If x is a list of numbers, x + 1 adds one to every element and sum(x) / size(x) is the mean. The same idea works for matrices and higher dimensions. It is the model behind NumPy, R, MATLAB, Julia and modern Fortran, and it is the whole language in APL, J and BQN.

Rank and Broadcasting

  • Rank — the number of dimensions: a scalar has rank 0, a list rank 1, a table rank 2.
  • Broadcasting — when shapes differ, the smaller array is stretched to fit, so matrix + row adds the row to every row of the matrix.
  • Reduction and scan — fold an array along an axis (sum, product, maximum) or keep the running results.
  • Outer product — apply a function to every pair of elements, producing a table. This is how an array language makes a multiplication table or all divisors.

Composition and Tacit Style

Array languages let you combine functions without naming their arguments. The average of a list is "sum divided by count", written in J as +/ % #. This tacit (point-free) style is close to functional programming, and the resulting programs are short enough to read at a glance once you know the vocabulary.

Why It Is Fast

Whole-array operations tell the machine exactly what to do to a large block of data. Implementations can use vector (SIMD) instructions, multiple cores and GPUs, and avoid the per-iteration overhead of an interpreter. Well-written array code is often faster than the equivalent loop in a scripting language.

Representative Languages

The first three are pure array languages. The last row shows the same ideas inside languages you may already know.

LanguageWhy study it
APLThe original: single-symbol primitives, right-to-left evaluation and the first tacit functions.
JAPL in plain ASCII, with verbs, adverbs, trains and rank as a central concept.
BQNA modern redesign with a more regular syntax and excellent documentation.
NumPy, R, MATLAB, JuliaArray ideas in mainstream languages, see Python, Julia and Fortran.

The Trade-offs

Array code is dense: a single line can replace a page. That is a strength for exploration and a weakness for readers who do not know the symbols. Very irregular problems (deep recursion, branching logic) fit array style poorly, and long chains of temporary arrays can use a lot of memory.