Useful APL snippets

Table of contents

Editors๐Ÿ”—

In RIDE, to display function trains in tree format:

    ]box ON -trains=tree
Was OFF -trains=box
    +/รทโ‰ข
  โ”Œโ”€โ”ผโ”€โ”
  / รท โ‰ข
โ”Œโ”€โ”˜
+

Basic array operations๐Ÿ”—

Turn a scalar into an array.

   ,5
5
   โด,5
1

First element of an array.

โŠƒ

Last element of an array. Note the lack of symmetry with โŠƒ.

โŠข/

Flatten an array.

{,โต}

Check that an array is a palindrome.

โŒฝโ‰กโŠข

Pad a number with a desired number of 0s.

    11โ†‘1 โ 1 followed by ten 0's.
1 0 0 0 0 0 0 0 0 0 0

Find the number of leading 1s in a boolean array.

    +/โˆง\

Numbers๐Ÿ”—

Sign of a number.

ร—

Get the integral and fractional part of a non-negative real number.

0 1โˆ˜โŠค

Profiling๐Ÿ”—

Compare the performance of 3 functions F, G and H on the same input s.

'cmpx' โŽ•CY 'dfns'
cmpx 'F s' 'G s' 'H s'

Sorting๐Ÿ”—

Sort an array in ascending order.

{โต[โ‹โต]}

Order the rows of a matrix according to the sorted order of the second row.

    โŠข mat โ† 2 3 โด 1 4 2 5 9 7
1 4 2
5 9 7
    mat[; โ‹mat[2;]]
1 2 4
5 7 9

Find the index of the maximum element of an array. Recall that in APL indices start at 1.

โŠƒโ’

Strings๐Ÿ”—

All uppercase English letters.

    โŽ•A
ABCDEFGHIJKLMNOPQRSTUVWXYZ

All lowercase English letters.

    โŽ•UCS 96+โณ26
abcdefghijklmnopqrstuvwxyz

Discard all characters except English letters.

    a โ† 'The quick brown fox! Jumps over the lazy... dog?'
    aโˆฉโŽ•A,โŽ•UCS 96+โณ26
ThequickbrownfoxJumpsoverthelazydog

Convert a string to lowercase.

    โŽ•C 'dYALog`
dyalog
    ยฏ1 โŽ•C 'dYALog`
dyalog

Convert a string to uppercase.

    1 โŽ•C 'dYALog`
dyalog

Case-insensitive string comparison. Note the use of โฅ (over), which monadically applies its right function to both arguments, and then dyadically applies its left function to the results.

    'Dyalog' โ‰กโฅโŽ•C 'DYALOG'
1

Check that a string is a palindrome after discarding non-alphabet characters. We convert to uppercase, discard everything that is not an uppercase letter, and then check that the result is a palindrome.

{(โŒฝโ‰กโŠข) โŽ•Aโˆฉโจ1โŽ•C โต}

Mathematics๐Ÿ”—

Generate an identity matrix.

โˆ˜.=โจ โณ

This is basically a tacit rephrasing of

{(โณโต)โˆ˜.=โณโต}

The following method is about as fast as it gets for generating an identity matrix. Right-pad 1 with โต zeroes and then repeat that array until the shape is โต โต.

{โต โตโด(โต+1)โ†‘1}

This can be rephrased in tacit form as a 5-train. Note that we use ร— (sign) to replace the positive input with 1. We could also use 1โจ or โ‰ข instead of ร—.

,โจโด+โˆ˜1โ†‘ร—

Generate a random float between 0 and 1.

?0