Using apl magics

An introduction to aplnb

aplnb adds %apl and %%apl functions to Jupyter and IPython, which exectute expressions in Dyalog APL.

Installation

First, install Dyalog APL. Dyalog provides a basic license for free. Once Dyalog is installed, install aplnb with:

pip install aplnb

Once that’s complete, you can install the magics to all IPython and Jupyter sessions automatically by running in your terminal:

aplnb_install

Usage

After first running an apl magic in a notebook, the APL language bar by Adám Brudzewsky is automatically added to the current page. (There is one change to Adám’s original version, which is that you can type a backtick twice in a row to enter triple backticks. To get a glyph, type backtick-q.)

You can use either a cell magic (%%ai) or a line magic (%ai). In either case the expression is evaluated and returned:

%%apl
y←⍳3
z←y×y
[1, 4, 9]
%apl 3×⍳4
[3, 6, 9, 12]
%apl ⎕A
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

You can store the value of an expression in a python variable using the line magic. Scalars, lists, and nest lists are used:

z = %apl z
print(z)
[1, 4, 9]

To avoid having the expression returned and/or displayed, end the last line with a ;.

%%apl
a←2 2 ⍴ ⍳4;

You can print from cell magics using the standard APL ⎕ glyph:

%%apl
⎕←a;
1 2
3 4

To use numpy, just pass the result of %apl into np.array:

import numpy as np
a = %apl a
np.array(a)
array([[1, 2],
       [3, 4]])

Example algorithms

The fibonacci sequence:

%apl {⍵,+/¯2↑⍵}⍣151 1
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597]

Explanation:

  1. 1 1: Initial seed (first two Fibonacci numbers)
  2. {⍵,+/¯2↑⍵}: Function that appends the sum of the last two elements
  3. ⍣15: Apply the function 15 times
  4. : Identity function, passes the initial argument (1 1) to the iteration

Prime number sieve:

%%apl
primes ← {⍵×2=+0=⍵∘.|⍵}⍳
(primes 50)~0
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

Explanation:

  1. ⍳50 generates integers 1 to 50
  2. ⍵∘.|⍵ creates a 50x50 matrix of divisibility (1 if divisible, 0 if not)
  3. 0= inverts the matrix (1 for non-divisible)
  4. +⌿ sums columns, counting non-divisors for each number
  5. 2= checks if count equals 2 (prime property)
  6. ⍵× multiplies result with original numbers, keeping primes
  7. ~0 removes zero from the result

Learning APL

To start learning APL, follow the 17 video series run by Jeremy Howard, and have a look at the study notes. Note however that the comments there about using commands starting with ], such as ]Help ≠, will not work with aplnb, so you should skip them.