Grading and Sorting#
There is no sort primitive in APL, although sorting can be easily achieved with the use of ⍋
(grade up) or ⍒
(grade down).
⍋
takes an array and returns the indices of the major cells in ascending order. From the least major cell to the greatest major cell. It is easiest to understand with an example:
V←3 1 4 1 5
⍋V
This means that the smallest element is the second one (1
), then the forth (also 1
), then the first (3
), etc.
So, we can use this to sort the array:
V[⍋V]
It works on arrays of any rank greater than 0:
M←3 2⍴2 7 1 8 2 8
M
⍋M
So the first is row 2 (1 8
) then row 1 (2 7
) then row 3 (2 8
). This is a lexicographic ordering - The cells are compared item by item, until there is a difference.
Characters are compared using their Unicode codepoints:
Greeting←5 2⍴'HelloWorld'
Greeting
⍋Greeting
Greeting[⍋Greeting;]
To sort an array of any rank, one can define a function:
sortUp←{(⊂⍋⍵)⌷⍵}
sortUp 1 4 1 5 1 6 1 7
⍒
is grade down. It behaves in the same way as ⍋
but grade in descending order.
sortDown←{(⊂⍒⍵)⌷⍵}
sortDown 11 5 3 23 7 17 2 13 19
As of version 17, you can grade any array (as long as it doesn’t contain refs). The rules for this are complicated and can be found on the Dyalog web help for Total Array Ordering.
sortUp 'carpet' 'car' 'cards' 'train' 'tram'
⊢ (2 2⍴2 5 1 3) (2 5 1 3) (1 4⍴2 5 1 3) '2513' 'abc' (3 2 2⍴'x')
Grading can be used for more than just sorting. To get the index of the maximum value in an array, you use ⊃⍒
:
⊃⍒6 3 2 1 88 32 6 10.7
{⍋⍋⍵}
is another useful function. While ⍋⍵
gives the indices that sort ⍵
, ⍋⍋⍵
gives the positions that each element of ⍵
would occupy after sorting. You can also think of ⍋
as inverting the permutation you give it.
A←4 6 8 1 2 4
⍋⍋A
The first element (4
) is the third smallest element, the second element (6
) is the fifth smallest, and so on. It is fairly common to use ⍋⍋
to normalise a vector, V
, to a permutation of ⍳≢V
which has the same ordering as V
.
Dyadic Grade#
Grade can also be used dyadically for character arrays. {⍺⍋⍵}
will grade ⍵
according to the alphabet ⍺
.
'aeioubcdfghjklmnpqrstvwxyz'⍋'helloworld'
{⍵['aeioubcdfghjklmnpqrstvwxyz'⍋⍵]}'helloworld'
There we sorted the vowels before the consonants. If characters are missing from the alphabet, they will be considered after the alphabet, and equivalent:
'abcdefgh'⍋'hawl'