Welcome to the APL Quest

Welcome to the APL Quest#

Today’s quest is the first from the 2017 round of the APL problem-solving competition.

We are given a number, and we are supposed to generate odd numbers, specifically that many of them. This is a really simple problem in APL.

To start off, we create a Lambda function and let’s say we give it the argument 5. This goes on the right, similar to how you could have say a minus sign with a 5 on the right. Here’s a basic example of generating the first 5 numbers using APL:

{}5
⍝ 1 2 3 4 5

Inside the function, we refer to the argument with (Omega) because the argument is on the right, and it’s the rightmost character of the Greek alphabet. This is useful to separate it from all identifiers that the programmer makes, which are written in the Latin alphabet.

Generating the Sequence#

Since we are supposed to generate a sequence of this length, we would use the index generator function denoted by iota. This gives us numbers from 1 to 5, but we only want every other number. So, we need a multiplication factor of 2.

Here’s how we can get the first 5 even numbers:

{2×⍳}5
⍝ 2 4 6 8 10

Multiplication automatically applies to all the elements generated by iota. However, our values are too large, so we need to subtract 1, or alternatively, we could add -1.

Note that the high minus () which APL uses distinguishes between negative numbers from subtracting and negation. If I had used a low minus, we would have gotten twice the indices added to 1 and then negated the whole bunch, which is not what we want.

We can create the sequence of odd numbers directly with the following expression:

{¯1+2×⍳}5
⍝ 1 3 5 7 9

This can also be expressed without the function brackets directly:

(¯1+2×⍳)5
⍝ 1 3 5 7 9

And we can define a named function too:

Odd¯1+2×⍳
Odd 5
⍝ 1 3 5 7 9

Function Patterns#

So while this is a solution, it follows a very simple pattern where we have a function that’s adverbially applied to the argument, and then we have another additive function with a parameter on the left. This pattern can be repeated: as long as you have this arrangement where every other thing in the expression is an adverbial function, and every other thing is either a parameter or something else, we can keep going like this.

One way to convert this into a tested function is by not mentioning the argument. Instead, we can just put parentheses around to signify it as a new derived function. This new function would be −1 + 2 × iota.

This works very nicely, and we require parentheses to distinguish it as a separate function, but of course, an expression would work as well. If we want to give it a name, then we do not need the parentheses either.

And that’s it for today! Thank you for watching.