man apl/gnu-apl

How GNU APL sorts and stores arrays

lib / APL 7 mindraft

checked against: GNU APL 2.0

What is an APL array once it is inside the interpreter, and what does ⍋ do with it? APL makes arrays look like the only data type there is. Every implementation still has to choose how to lay them out in memory and how to sort them. I read the source of GNU APL 2.0, the GNU project’s interpreter for ISO 13751 APL, and checked what I read against the Homebrew build on an Apple M2 Pro.

The short version

  • An array is a Value: a 176-byte header plus its elements. A value of up to 12 elements keeps them inside the 464-byte object; a longer one gets a separate block.
  • Every element is a 24-byte Cell object with a vtable pointer, whatever it holds, whether a boolean, a character, a 64-bit integer, a double or a pointer to a nested array.
  • Integers are 64-bit, and arithmetic switches to floating point when a result would pass 9.2 × 10¹⁸, a little before 2⁶³.
  • ⍋ and ⍒ are a heapsort over a list of positions, made stable by comparing positions when the values are equal. Unique (∪) and Index Of (⍳) reuse the same heapsort.

A value and its cells

Value.hh declares the Value class: shape, flags, an owner count for reference counting, a pointer to the elements (the ravel) and a fixed array short_value of SHORT_VALUE_LENGTH_WANTED cells. apl --cfg prints the numbers this build was configured with:

$ apl --cfg 2>&1 | grep -A3 SHORT_VALUE
    SHORT_VALUE_LENGTH_WANTED=12, therefore:
        sizeof(Value)       : 464 bytes
        sizeof(Cell)        :  24 bytes
        sizeof(Value header): 176 bytes

176 + 12 × 24 = 464. The constructor in Value.cc returns early when the length is at most 12, and the ravel points at short_value. Longer values call new char[length * sizeof(Cell)] (lines 104 to 142). So a scalar or a short list costs one allocation of 464 bytes, and a long list costs 464 bytes plus 24 per element.

value of length ≤ 12               value of length > 12
+-------------------------+        +-------------------------+
| header (176 bytes)      |        | header (176 bytes)      |
|  shape, flags, owners   |        |  ravel ---------------------+
|  ravel --+              |        | short_value (unused)    |   |
| short_value[12] <--+    |        +-------------------------+   |
|  12 cells x 24 bytes    |                                      v
+-------------------------+        +----------+----------+-------+--
                                   | cell 24B | cell 24B | ...
                                   +----------+----------+---------

A Cell (Cell.hh) has no fields except one union, SomeValue: a 64-bit integer, a character code, two doubles for a complex number, a float with an optional rational denominator, or a pointer to a nested value plus its owner. The union is 16 bytes. The class has virtual functions, so each cell also holds a vtable pointer, and the subclasses IntCell, FloatCell, CharCell, ComplexCell and PointerCell are told apart by that pointer alone.

There is no smaller storage for booleans. = writes its result with IntCell::zI (Cell.cc, line 264), a full integer cell. The interpreter keeps a running total of ravel bytes, which ⎕SYL shows:

      ⎕SYL[6;]
 current total ravel bytes 14352
      Q←1000000⍴1
      ⎕SYL[6;]
 current total ravel bytes 24014352

A million 1s, 24 million bytes. A nested array spends a whole Value on each item. Cutting a list of 100,000 integers into 43,282 runs with partitioned enclose added 43,289 to the “current number of values” counter in ⎕SYL, one per run plus a few temporaries.

Integers and when they become floats

APL_Integer is a 64-bit integer. Multiplication in IntCell::bif_multiply (IntCell.cc, lines 568 to 587) multiplies the two numbers as doubles first. If that product is above LARGE_INT or below SMALL_INT, the result is a float cell; otherwise it multiplies again as integers. SystemLimits.def sets those limits to ±9,200,000,000,000,000,000, which is 23 × 10¹⁵ short of 2⁶³ − 1:

      3000000000×3000000000
9000000000000000000
      3100000000×3000000000
9.3E18
      2⋆62
4611686018427387904
      (2⋆62)×2
9.223372037E18

The last one is 2⁶³, which can’t be a signed 64-bit integer anyway. Floats print with ⎕PP, the print precision, which defaults to 10 digits. Integers print in full.

Grade is a heapsort

⍋B and ⍒B land in Bif_F12_SORT::sort (Bif_F12_SORT.cc, lines 154 to 174). It calls Cell::sorted_indices, which fills a vector with 0, 1, …, n−1 and hands it to Heapsort<ShapeItem>::sort with one of two comparison functions, greater_cp for ⍋ and smaller_cp for ⍒ (Cell.cc, lines 302 to 326). The heapsort itself is a textbook one in Heapsort.hh: build a heap from the middle of the array towards the root, then repeatedly swap the root to the end and sift the new root down. It sorts in place, needs no memory beyond the index vector, and is O(n log n) in every case.

Heapsort is not stable. The swaps move equal elements past each other. GNU APL gets a stable grade anyway, because the comparison never returns “equal”. When the cells compare equal, greater_cp and smaller_cp both end with return A > B;, comparing the two positions (Cell.cc, lines 226 and 246). Every pair of positions is then strictly ordered, and the only order consistent with that is the stable one:

      ⍋ 2 1 2 1
2 4 1 3
      ⍒ 2 1 2 1
1 3 2 4
      ⌽⍒ 2 1 2 1
4 2 3 1

The last line is the usual trap. Reversing a descending grade gives an ascending order, but equal values come out in reverse index order, so ⌽⍒ is not ⍋ when there are ties.

For a matrix, comp_len is the row length, and the comparison walks the row cell by cell before it falls back to the positions. Each comparison is a virtual call, Cell::compare, which for two integers is a plain < and == (IntCell.cc, lines 848 to 864).

How much does the input order matter? I timed ⍋ on a million integers inside one script, using ⎕FIO[50] 1000, which returns the time of day in milliseconds:

input, 1,000,000 integers⍋, three runs (ms)
sorted, ⍳1000000301, 306, 300
reversed, ⌽⍳1000000310, 318, 305
shuffled, 1000000?1000000608, 665, 634
all equal, 1000000⍴7166, 173, 171

⍒ on the shuffled list took 651, 600 and 646 ms. ∪ took 704, 647 and 656 ms on the shuffled list and 161, 158 and 162 ms on the constant one.

A heapsort doesn’t notice that its input is already sorted the way an adaptive sort like Timsort does. Sorted input still took about half as long as shuffled input here.

Unique and Index Of sort too

Monadic ∪ (PrimitiveFunction.cc, lines 1581 to 1619) makes a vector of pointers to the cells and heapsorts it with Cell::compare_stable, which again breaks ties by address. It walks the sorted pointers and keeps the first of each group of equal values, using equal with the comparison tolerance ⎕CT. Then it heapsorts the survivors a second time by address, which puts them back in their original order. Two sorts give ∪ its first-appearance order:

      ∪ 3 1 3 0 3 1
3 1 0

Dyadic ⍳ (Index Of) uses the heapsort when it pays off. If the left argument has at least 64 items and the right one more than 5, it grades the left argument once and binary-searches it for each item on the right (Bif_F12_INDEX_OF.cc, lines 120 to 131). Otherwise it scans the left argument and stops at the first match (Bif_F12_INDEX_OF.hh, line 53).

Curious facts

  • ⌸ (Key) is in GNU APL’s character table (Avec.def, line 242), but nothing implements it. {⍺,≢⍵}⌸X is a SYNTAX ERROR. So is a three-function train such as (+/÷≢) 1 2 3.
  • GNU APL 1.0 already used a heapsort for grade, and already broke ties by position (“a and b are equal: sort by position”, Cell.cc in 1.0). It built its array of cell pointers as a variable-length array on the C stack (PrimitiveFunction.cc line 2124 in 1.0).
  • Value.cc contains try_implode, which packs a boolean array into 64 bits per word. In 2.0 nothing calls it.
  • ⍎ treats a line feed like a blank: the tokenizer skips both (Tokenizer.cc, lines 375 to 377). ⍎ on a whole file of numbers, one per line, returns them as one list.
  • )OFF always prints a line feed before it exits (Command.cc, line 1618), so a script that prints its result with ⍞←, which adds no line end, still ends with one.

History

  • October 2013: the newest files in the apl-1.0 tarball on ftp.gnu.org are dated 13 October 2013, the same date as its gzip header. Grade is Cell::heapsort.
  • March 2026: the newest files in the apl-2.0 tarball are dated 15 March 2026. The heapsort has moved into its own template, Heapsort.hh.

Sources

GNU APL 2.0, Subversion tag apl-2.0 (identical to apl-2.0.tar.gz, sha256 24bbb744fce47e62837234a053bdeecee51b9ea61c82c79f7cc191bc6a54c0a1). Links go to raw files; line numbers are given in the text.

ls apl/