# Tips for golfing in APL

I started one code golf challenge recently and it seems like the winner is GolfScript (surprise, surprise!). What's interesting is that there was another very strong competitor that had all chances to win over GolfScript. Its name is APL. I see a lot of answers written in APL here. It seems like this language is fairly efficient for code golfing, so I decide to ask for any code golfing tips you know for APL programs. Feel free to post some code examples. It is usually very interesting to see language in action.

Edit: for people reading this who don't know APL at all but want to take it up, Mastering Dyalog APL is a very good resource.

1. Evaluation is strictly right-to-left. This includes setting variables, so take advantage of it.

2+a, 1+a←1 -> 3 4

a is set to 1, 1+a evaluates to 2, a,2 evaluates to 1 2 and 2+1 2 evaluates to 3 4.

2. Like C, ← can be combined with a function, i.e. a +← 3. Unlike C, this is generic: foo F← bar sets foo to F bar. Somewhat unintuitively, as an expression this returns bar, not F bar.

It works with anonymous functions too:

      a←0
a+←3 ⋄ a
3
a+←3 ⋄ a
6
a { ⍵/'!' } ←4 ⋄ a
!!!!

3. You can assign to an array: A←8, like you'd expect. But you can also assign multiple items at the same time: A[3 5 6]←9 1 4, or even A[3 5 6]←9, setting them all to the same item. You can, of course, add a function to the ← here too. The function will then be applied to each element separately, as if you did F¨.

4. ⍨ is your friend, even if he doesn't look too happy about it.

1. If F is dyadic, dyadic ⍨ switches the arguments: a F b <-> b F⍨ a. This comes in handy when golfing because it can save you from using braces:

(F G H x) K y      <->     y K⍨ F G H x


This does change the evaluation order, as the right hand is always evaluated before the left hand.

2. If F is dyadic, monadic ⍨ applies the same argument to both sides of the function:

      5⍴5
5 5 5 5 5
⍴⍨5
5 5 5 5 5


The argument is only evaluated once. This particularly comes in handy with outer products, i.e. to compare each value in an array with the other values in the same array, you can use ∘.=⍨ instead of having to do x∘.=x←(whatever).

3. If F is monadic, ⍨ does nothing, but it does separate the function from the argument. So it can still save you braces if the function is complex:

      {⍵+3}⍣5 6
∇{⍵+3}
∇ ⍣ 5 6
({⍵+3}⍣5)6
21
{⍵+3}⍣5⍨6
21

5. Learn the idioms! Then golf the idioms. For example:

((((1↑⍴X),⍴Y)↑X)^.=Y)⌿X


can be mechanically transformed into:

X⌿⍨Y^.=⍨X↑⍨(1↑⍴X),⍴Y


and then further into:

X⌿⍨Y^.=⍨X↑⍨(⊃⍴X),⍴Y


⊃ (first) being equivalent to 1↑ (take one) in this case. And possibly:

X⌿⍨Y^.=⍨X↑⍨(≢X),⍴Y


≢ (tally) being equivalent to ⊃⍴ (the first element of the shape) for all but scalars.

• Is there a way to get a free license beside having the raspberry pi version? – Fabinout Jan 27 '14 at 17:39
• A legal way to get it, obviously. – Fabinout Jan 27 '14 at 18:01
• @Fabinout: At dyalog.com you can download a free Windows version. Click "Download Zone" and then "Unregistered Download". It will nag you to register but otherwise it's fully functional and free and legal. If you're a student, you can get the normal version for free by filling out a form. If you don't live in a country where they ruin your life for pirating, well, you know what to do. – marinus Jan 27 '14 at 18:06
• There is also Nars2000, an open source implementation that has many more features than Dyalog (and some bugs.) Some of its features come in handy for golfing, such as the prime number functions or multisets. – Tobia Mar 2 '14 at 10:58
• There is GNU APL. – Mohammad Alaggan Jan 3 '15 at 13:11

# Trains

A(f g h)B      ←→  (A f B)g A h B  ⍝ fork
(f g h)B      ←→  (  f B)g   h B  ⍝ fork
A(  g h)B      ←→         g A h B  ⍝ atop
(  g h)B      ←→         g   h B  ⍝ atop
(A g h)       ←→  ({A} g h)       ⍝ "Agh" fork
(f g h k)     ←→  (f (g h k))     ⍝ 4-train
(f g h k l)   ←→  (f g (h k l))   ⍝ 5-train, etc
(f g h k l m) ←→  (f(g h(k l m))) ⍝ groups of 3 from the right, last could be 2
f∘g B        ←→    f g B         ⍝ "compose" operator, useful in trains
A f∘g B        ←→  A f g B

• Does that mean that for the sake of future readers, we shouldn't tell Oberon how to shorten it? – Adám Jan 30 '18 at 7:11
• No, do as you normally would on PPCG. I'll remove that line after the expression reaches (what I believe to be) its shortest. It's an easy exercise - I don't think you personally would benefit from it. – ngn Jan 30 '18 at 9:29
• I can get it down to 16, but I'm not using any of your tips, so maybe I'm way off. – Adám Jan 30 '18 at 10:37
• @Adám well, you are using a train :) mine was similar but longer because I didn't think of ⎕ML – ngn Jan 30 '18 at 13:11
• Isn't it "groups of 3 from the right"? – Adám Mar 15 '18 at 14:56

# Use ⊥ to combine multiplication with addition

(a×b)+C  ->  a⊥b,C
(C)+a×b  ->  a⊥b,C
(a×b)-C  ->  a⊥b,-C


Assumptions:

• a and b are terms that don't require further parentheses when used as a left argument

• C is an expression that may need parentheses when used as a left argument

• a b C evaluate to numeric scalars

## Tricks for dealing with / and ⌿ in trains

When using trains you may want to use reductions f/ like sum +/ or even replicate reduction // . However, if your train has more parts to the left of the reduction you need parentheses to create an atop. Here are some tricks to save bytes.

### Use 1∊ instead of monadic ∨/ or ∨⌿ on Boolean arrays

Task: Given two equal-length strings A and B, return 2 if any corresponding characters of A and B are equal, 0 otherwise. E.g. A←'abc' and B←'def' gives 0 and A←'abc' and B←'dec' gives 2.

A dfn solution may be A{2×∨/⍺=⍵}B but you want to shorten it by going tacit. A(2×∨/=)B is not going to work because the rules of train formation parse this as 2 (× ∨/ =) but you want 2 × (∨/=) .

Observe that ∨/ or ∨⌿ on a Boolean vector (∨/, or ∨⌿, for higher rank arrays) asks whether there is any 1 present, i.e. 1∊ , so we can write our train as 2×1∊= .

Note that ∊ ravels its right argument, so you cannot use it to reduce each row or column separately.

### Use 1⊥ instead of monadic +/ or +⌿

Task: Given a list of lists L and an index N, return thrice the sum of the Nth list. E.g. L←(3 1 4)(2 7) and N←1 gives 24.

A dfn solution may be N{3×+/⍺⊃⍵}L but you want to shorten it by going tacit. N(3×+/⊃)L is not going to work because the rules of train formation parse this as 3(× +/ ⊃) but you want 3 × (+/⊃) .

Observe that evaluating a list of numbers in unary (base-1) is equivalent to summing the list because ∑{a, b, c, d} = a + b + c + d = (a × 1³) + (b × 1²) + (c × 1¹) + (d × 1⁰). Therefore +/a b c d is the same as 1⊥a b c d , and we can write our train as 3×1⊥⊃ .

Note that on higher-rank arguments, 1⊥ is equivalent to +⌿.

### Use f.g instead of f/g with scalar and/or vector arguments

Task: Given a list L and a number N, return the range 1 thorough the number of minimum division remainder when the elements of L are divided by N. E.g. L←31 41 59 and N←7 gives 1 2 3.

A dfn solution may be N{⍳⌊/⍺|⍵}L but you want to shorten it by going tacit. N(⍳⌊/|)L is not going to work because the rules of train formation parse this as ⍳ (⌊/) | but you want ⍳ (⌊/|) .

The inner product A f.g B of scalar two functions when the arguments are scalars and/or vectors is the same as f/ A g B because both are (A g B) f (A g B) f (A g B) etc., so we can write our train as ⍳⌊.| .

Note that this does not work for higher-rank arrays.

### Use ∊⊆ instead of / with Boolean left and simple vector right arguments

Task: Given a list L and a number N, filter the list so that only numbers greater than N remain. E.g. L←3 1 4 and N←1 gives 3 4.

A dfn solution may be N{(⍺<⍵)/⍵}L but you want to shorten it by going tacit. N(</⊢)L is not going to work because the binding rules will parse this as (</) ⊢ but you want / to be the function replicate rather than the operator reduce.

Dyadic ⊆ with a Boolean left argument partitions the right argument according to runs of 1s in the left argument, dropping elements indicated by 0s. This is almost what we want, save for the unwanted partitioning. However, we can get rid of the partitioning by applying monadic ∊. Thus {(⍺<⍵)/⍵} can become {∊(⍺<⍵)⊆⍵} and thus we can write our train as ∊<⊆⊢ .

Note that this does not work for higher-rank arrays.

### Use ∊⍴¨ instead of / with non-Boolean left and simple vector right arguments

Task: Given a list L, replicate Nth item N times. E.g. L←3 1 4 gives 3 1 1 4 4 4.

A dfn solution may be {(⍳⍵)/⍵}L but you want to shorten it by going tacit. (⍳/⊢)L is not going to work because the binding rules will parse this as (⍳/) ⊢ but you want / to be the function replicate rather than the operator reduce.

Dyadic ⍴ combined with ¨ copies each element of the right argument according to the matching element in the left argument. This is almost what we want (e.g. 1 2 3⍴¨3 1 4 → (3)(1 1)(4 4 4)). Then, we can get rid of the nesting by applying monadic ∊. Thus {(⍳⍵)/⍵} can become {∊(⍳⍵)⍴¨⍵} and thus we can write our train as ∊⍳⍴¨⊢.

Note that this does not work for higher-rank arrays.

### Use 0⊥ instead of ⊢/ or ⊢⌿ with numeric arguments

Task: Given a list L and a number N, multiply the N with the rightmost element of L. E.g. L←3 1 4 and N←2 gives 8.

A dfn solution may be N{⍺×⊢/⍵}L but you want to shorten it by going tacit. N(⊣×⊢/⊢)L is not going to work because the rules of train formation parse this as ⊣ (× ⊢/ ⊢) but you want ⊣ × (⊢/⊢) .

Observe that 0⊥ on a numeric array is the same as ⊢⌿ , so we can write our train as ⊣×0⊥⊢ .

Note that this selects the last major cell of higher-rank arrays.

• Maybe you could add this chat answer to this one? – J. Sallé Jan 17 '18 at 15:29

# Complex numbers

Often overlooked, they present wonderful opportunities to shorten expressions dealing with grids, mazes, fractals, or geometry.

0j1⊥¨    0j1⊥   ⍝ pair(s) of reals -> complex
11 9∘○¨  11 9○  ⍝ complex -> pair(s) of reals
|z0-z1          ⍝ distance between two points
0j1×z   0j¯1×z  ⍝ rotate by ±90° around (0,0)
0j1*⍳4          ⍝ the four cardinal directions
+z       -+z    ⍝ reflect across x or y axis
+\0,z           ⍝ sequence of steps -> path
¯2-/z           ⍝ path -> sequence of steps
0j1⊥¨n-⍳2⍴1+2×n ⍝ lattice centred on (0,0)


# Generate A001057, A130472, and many variations

A001057 is a simple sequence of alternating integers, starting with 0, 1, -1, 2, -2, 3, -3, .... A130472 is its negation, 0, -1, 1, -2, 2, -3, 3, ....

APL has a surprisingly short way to generate nth term or first n terms:

### nth term of A001057 (0-indexed)

⎕IO←1
-/⍳


Try it online!

### nth term of A130472 (1-indexed)

⎕IO←0
-/⍳


Try it online!

### first n terms of A001057, leading 0 removed (1, -1, 2, -2, ...)

⎕IO←1
-\⍳


Try it online!

### first n terms of A130472 (0, -1, 1, -2, 2, ...)

⎕IO←0
-\⍳


Try it online!

Applying various primitive functions to these sequences can give many interesting results which are shorter than other alternatives:

• 1, 1, 2, 2, 3, 3, ...: With ⎕IO←1, |-\⍳n is shorter than n↑2/⍳n in explicit form
• 0, 1, 1, 2, 2, 3, ...: With ⎕IO←0, |-\⍳n is shorter than ⌈2÷⍨⍳n in explicit form
• 0, 1, 0, 2, 0, 3, ...: With any ⎕IO, |0⌊-\⍳n or -0⌊-\⍳n is shorter than any known alternatives, both tacit and explicit
• 0, -1, 0, -2, 0, -3, ...: With any ⎕IO, 0⌊-\⍳n
• 1, 0, 2, 0, 3, 0, 4, ...: With ⎕IO←1, 0⌈-\⍳n
• 0, 1, 1, 0 repeated: With ⎕IO←0, 2|-\⍳n
• 1, 1, 0, 0 repeated: With ⎕IO←1, 2|-\⍳n
• Reverse odd then forward even, e.g. 7 → 5 3 1 0 2 4 6: ⍋-\⍳n with ⎕IO←0. ⎕IO←1 gives 7 → 6 4 2 1 3 5 7.
• Permutation of 0 to n-1, alternating front and end, e.g. 7 → 0 6 1 5 2 4 3: n|-\⍳n with ⎕IO←0.
• First n terms of A002620, 0, 1, 2, 4, 6, 9, 12, 16, 20, ...: -\-\⍳n with ⎕IO←0 (⎕IO←1 gives same sequence with leading zero removed), which is shorter than ⌊×⍨2÷⍨⍳n with ⎕IO←1.

# Indexing modulo vector length

⊃i⌽a is often shorter than the naive ⊃a[(≢a)|i] or a⊃⍨i|⍨≢a (where a is a vector and i is an integer, and ⎕io is 0)

a useful variation on this (thanks EriktheOutgolfer for pointing out) is: I↑Y⌽⍨I×X where Y is the concatenation of some length-I vectors and X is the index of the one we want to pick, for instance: 3↑'JanFeb...Dec'⌽⍨3×month

# Constant functions

=⍨ and ≠⍨ thanks to ngn.

Sometimes you just need a single value for each element of a list. While you might be tempted to use {value}¨, it is shorter to use value⊣¨ but for some common values, you can get even shorter (using ⎕IO←0):

¯1s with ⍬⍸list

0s with ⍬⍳list

1s with ⍬⍷list

Note that these only work on lists (though they may be nested). For higher-rank arrays, you can use the following to get all 0s and all 1s:

1s with =⍨

0s with ≠⍨

If you set ⎕ML←0, all numbers can be made into zeros (as if 0×) with:

∊

If you only need a single number, you may be able to use monadic ≡ to get 1 or 0 instead of using 1⊣ or 0⊣.

• "Sometimes you just need a single value for each element of a list." - It may be noteworthy: when that value is the first element of the list, you can use ⊣\  – ngn Feb 13 '18 at 0:17
• @ngn I'd say that ⊣ and ⊢ with / and ⌿ merit a post of their own. – Adám Feb 13 '18 at 0:20

# Use ⍨

### Avoid parentheses

⍨ (Commute) can save you bytes by avoiding parentheses. Whenever you have a function where the left argument needs to be parenthesised and the right argument does not, you can save a byte, e.g. (A<B)÷CC÷⍨A<B.

### Double arrays

To append a copy of an array to its end, use ,⍨A or ⍪⍨A.

### Double numbers

Instead of using 2∘× to double, you can use +⍨ since it adds the argument to itself: 1+2∘×1++⍨.

### Square numbers

Instead of using 2*⍨Y to square, you can use ×⍨Y since it multiplies the argument with itself: 2*⍨A+B×⍨A+B.

### Random permutation

?⍨N will give you a random permutation of length N.

### Self-classify

Find the indices of the first occurrence of each major cell with ⍳⍨A

### Count trailing 1s in a Boolean vector

Instead of +/∧\⌽B to count how many trailing 1s there are in N you can use ⊥⍨.

### Reverse composition

A f∘g B is A f g B, but if you want (g A) f B, use f⍨∘g⍨.

### Reverse reduce

f/ a1 a2 a3 is a1 f (a2 f a3). If you want (a1 f a2) f a3, use f⍨/⌽.

### Reverse scan

f\ A B C is
A (A f B) (A f (B f C)).

f⍨/∘⌽¨,\ A B C is
A (A f B) ((A f B) f C).

f⍨\⌽ A B C is
((A f B) f C) (B f C) C.

⌽f/∘⌽¨,\⌽ A B C. is
(A f (B f C)) (B f C) C.

# Enumerate the characters in a string without ⍳≢

Task: Given two strings, S and T, list the indices of their concatenation. E.g. S←'abcd' and T←'xyz' gives 1 2 3 4 5 6 7.

A dfn solution may be S{⍳≢⍺,⍵}T but you want to shorten it by going tacit. ⍳≢, is not going to work because the train parsing rules will parse this as (⍳)≢(,) but you want (⍳≢),.

Dyadic ⍋ with an empty left argument grades simple character arrays according to their current order, which is the same as ⍳≢. Thus {⍳≢⍺,⍵} can become {⍬⍋⍺,⍵} , so we can write our train as ⍬⍋, .

Note that this does not work for numeric or mixed arrays.

• Wow, didn't know that was a thing. – Zacharý Nov 10 '18 at 21:52

# Constructing a long complex string (char vector)

Original idea from @ngn.

We can (ab)use rotation n⌽ and enlist ∊ to shorten multiple concatenations:

'(',(⍺∇r),'|',(⍺∇s),')'
→ Rotate the last ')' to front and apply 1⌽
1⌽')(',(⍺∇r),'|',(⍺∇s)  (-1 byte)
→ We don't need parens at the end
1⌽')(',(⍺∇r),'|',⍺∇s    (-3 bytes in total)
→ Remove some concats(,) to use stranding instead and enlist(∊) later
1⌽∊')('(⍺∇r)'|',⍺∇s     (-4 bytes in total)


Note that we can't remove the last concat (,) in this case; otherwise the recursive call would be screwed up.

The ∊ trick can also be used to shorten construction of numeric arrays:

0,(⍳5),0
→
∊0(⍳5)0   (-1 byte)


# Miscellaneous ideas

Cross-post of my own J tip, because APL and J are so closely related that the two can share many ideas.

## If you're facing -⍨/, try ¯1⊥ instead

A common reason to use -⍨/ is to reverse-subtract over a length-2 axis, e.g. given a 2-element array x y, compute y-x.

If this is the case, ¯1⊥ is an equivalent expression; just like 2⊥x y computes 2x+y, ¯1⊥x y computes -x+y. While the two expressions have same length, ¯1⊥ is more likely to fit well in trains (due to being a dyadic primitive function with a left arg, vs -⍨/ being a monadic derived function).

Note that, if you apply it to longer axis, ¯1⊥ gives you more similar result to -/ (alternating sum), with negated result when the length is even.

## Construct a boolean square matrix where the border is ones/zeros and the interior is the opposite

This is mainly for large fixed-size matrices, say 6 by 6.

The matrix

1 1 1 1 1 1
1 0 0 0 0 1
1 0 0 0 0 1
1 0 0 0 0 1
1 0 0 0 0 1
1 1 1 1 1 1


can be generated by ∘.∨⍨ -ing the boolean vector 1 0 0 0 0 1. The shortest known way to generate that vector is 6⍴5↑1, so we can get the matrix above in just 9 bytes:

∘.∨⍨6⍴5↑1


We can also get negation of it at no extra cost, by swapping ∨ with ⍱! (Remember that APL has NOR ⍱ and NAND ⍲; they are rarely needed, but definitely are a byte saver when we do need them.)

# Base Conversions

The function b⊥v, where b is a numeric base and v is a vector of digit values in that base, converts the vector v into its decimal (base-10) equivalent. If you want to convert a base-10 number into base b, a naïve approach would be to try to use ⊤, but this requires figuring out (or calculating) how many digits the number would require in base b. Instead, use the Power operator ⍣ with a right operand of ¯1: (b∘⊥⍣¯1). This will invert the convert-to-decimal function to convert back to base b with exactly the minimum necessary number of digits in the base-b representation.

      2⊥1 1 0 1            ⍝ Convert the base-2 digit vector 1 1 0 1 to base-10
13
(2∘⊥⍣¯1)13           ⍝ Convert 13 to its base-2 digit vector
1 1 0 1

• Often, you don't need the ∘: 2(⊥⍣¯1)13 – Adám Jul 8 at 5:26

When you need to encode some arbitrary data (as is common in the Kolmogorov complexity questions), it can be achieved with a string of characters from the atomic vector ⎕AV.

For example, to encode the array 256 13 16 127 128 168 192 in Dyalog APL:

⎕AV[256 13 16 127 128 168 192]      ⍝ the result is: ⍣%⍵⊣⌷∧⊤


Then to decode it:

⎕AV⍳'⍣%⍵⊣⌷∧⊤'


Adám's SBCS (single byte character set) also allows to encode some other characters (⊆⍠⍤⌸⌺⍸) as a single byte.

• This, of course, only works if all your integers are 1≤n≤256 (or 0≤n≤255 with ⎕IO←0). If all your integers are 1≤n≤26 (or 0≤n≤25 with ⎕IO←0), you can use ⎕A instead of ⎕AV. – Adám Jul 8 at 5:31
• Another thing to note is that, if you're unlucky, you will get some chars like linefeed which can't be embedded in the string literal. – Bubbler Jul 8 at 8:15
• Well, I used it like this ∊(5 5 5⊤⊢)¯6+⎕AV⍳'ÏSSS9i⌶⌶⌶⌶RSÐSS'. In this case each byte is decoded into three numbers in range 0≤k<5. So you get 45 numbers from 15 characters. But I had to use an offset -6 because I was "unlucky". (And, of course, added logic worsens the "compression rate".) – Andriy Makukha Jul 8 at 13:24
• …Another trick here is to pick the string so that to avoid using ¨, of course. – Andriy Makukha Jul 8 at 13:36

# Repeat with intermediate results

This is originally @ngn's suggestion on an APL answer of mine.

While APL has the power operator ⍣ which can repeat a function certain number of times, it cannot collect intermediate results on its own (unlike J's ^: allowing <n or i.n right operand to do the job). Usually one would collect the intermediate results by using an auxiliary variable with modified assignment, or "hack" the left operand of ⍣ to something like (⊣/,f¨)⍣n⊂x, or naively write down the iterations like {⍵(f⍵)(f f⍵)}x.

But there is a clever way using scan ⊢∘f\. Since x ⊢∘f y ignores x and applies f to y monadically, such a scan over n copies of x (enclosed if x is non-scalar) gives the results of f applied to x 0..n-1 times:

  ⊢∘f\n⍴⊂x
→ ⊢∘f\x x x ... x
→ (x)(x ⊢∘f x)(x ⊢∘f x ⊢∘f x) ...
→ x(f x)(f f x)(f⍣3⊢x) ... (f⍣(n-1)⊢x)


This is shorter than several alternatives (assume x is a complex expression):

{⍵(f⍵)(f f⍵)}x  ⍝ way too long for 2nd or higher iterations
(⊣/,f¨)⍣n⊂x     ⍝ shorter, but still long
⊢∘f\n⍴⊂x        ⍝ shortest


Interestingly, the scan expression ties when compared to various expressions that collect only zeroth and first iterations:

{⍵(f⍵)}x  ⍝ dfn
(⊂,⊂∘f)x  ⍝ tacit
y(f y←x)  ⍝ intermediate assignment; this wins if f is a single primitive
⊢∘f\2⍴⊂x  ⍝ scan


Also note that ⊢∘f\n⍴⊂ without the right arg is also a valid train.

• some times is better not be clever – user58988 Jul 18 at 10:28