A tangled loop of gray wire on the left; on the right the wire runs straight through four rows of glowing blue cubes: a rising staircase, cubes stepping up and down between neighbors, cubes leveled around a center line, and short stacks like a bar chart

Episode 5 of my video series on array programming is about idioms. Episode 4 was about what happens when arrays of different shapes meet. This one is about thinking without loops: small problems you would usually solve with a loop, each solved again with whole arrays.

One pattern for each idiom

An idiom is a short phrase for a pattern that keeps coming back. Each idiom in this episode follows one pattern: first the problem, then a loop that solves it (in Rust), then the idiom, and what it costs.

The examples use three small lists:

x ← 3 1 4 1 5 9
s ← 2 4 6 8
votes ← 2 3 2 1 2 3

Idioms you have met

Why are a few names one letter and a mark? Most X_eTaL built-ins are words with one underlined letter: r̲ev, r̲eshape, t̲ally, d̲rop. The underline marks a function name (typed as an underscore after the letter, r_ev), and a word, because one letter cannot stand for every word that starts with it. A name ends in a mark only where that mark already means something in APL, so just four read like the APL symbols they come from:

Name Does APL
r̲/ (r_/) reduce /
s̲\ (s_\) scan \
o̲- (o_-) rotate, first axis ⊖
o̲\ (o_\) transpose ⍉

The letter names the kind (r for reduce, s for scan); o stands in for APL’s circle. One other mark ends a name: a ? marks a yes-or-no question, as in m̲ember?.

Some idioms have come up already. Plus reduce sums a list, and a comparison followed by a sum counts the matches:

'+ r̲/ x       ⍝ 23
'+ r̲/ x > 3   ⍝ 3

Reverse and rotate rearrange the items, and no index appears anywhere:

r̲ev x    ⍝ 9 5 1 4 1 3
2 o̲- x   ⍝ 4 1 5 9 3 1

Running totals: scan

The episode's slide: plus scan of x, the boxed list 3 1 4 1 5 9 becomes 3 4 8 9 14 23
From the video: plus scan keeps every running sum. Click to enlarge.

The first new problem is running totals: each item becomes the sum of everything up to it. A loop keeps a total and saves it after each step:

let mut total = 0;
for v in &x {
    total += v;
    out.push(total);
}

In X_eTaL this is a scan. Plus scan keeps every running sum, and the last one is the total:

'+ s̲\ x
┌→────────────┐
│3 4 8 9 14 23│
└~────────────┘

Scan works with any function. Max scan keeps the largest value so far:

'm̲ax s̲\ x
┌→──────────┐
│3 3 4 4 5 9│
└~──────────┘

The trade-off: scan keeps every step, not only the last.

Adjacent changes: shift and subtract

The episode's slide: 1 drop x minus negative 1 drop x is -2 3 -3 4 4; compared with greater than, 0 1 0 1 1
From the video: subtract the shifted lists, or compare them. Click to enlarge.

Next, adjacent changes: how much each item differs from the one before it. A loop starts at the second item and looks back one:

for i in 1..x.len() {
    out.push(x[i] - x[i - 1]);
}

The idiom shifts the list instead of looking back. Drop the first item, then drop the last, and the two lists line up, each item beside the one before it:

1 d̲rop x    ⍝ 1 4 1 5 9
-1 d̲rop x   ⍝ 3 1 4 1 5

Subtract them item by item. The result has one item fewer than the list. Compare instead, and you find every rise:

(1 d̲rop x) − -1 d̲rop x   ⍝ -2 3 -3 4 4
(1 d̲rop x) > -1 d̲rop x   ⍝ 0 1 0 1 1

Normalize values: an aggregate, then each item

The episode's slide: plus reduce of s divided by its tally is 5.0; float s minus that is -3.0 -1.0 1.0 3.0
From the video: an aggregate, then each item. Click to enlarge.

Next, normalize values: subtract the average from every item. A loop needs two passes, the first to find the average and the second to subtract it:

let mean = s.iter().sum::<f64>() / n;
for v in &s {
    out.push(v - mean);
}

The idiom is an aggregate, then an item-by-item step. Reduce and divide give the average, a single value, and scalar extension from episode 4 does the rest:

('+ r̲/ s) ÷ t̲ally s                ⍝ 5.0
(f̲loat s) − ('+ r̲/ s) ÷ t̲ally s   ⍝ -3.0 -1.0 1.0 3.0

One detail: division gives a float, and these items are integers. In X_eTaL the two do not mix, so without f̲loat it is an error:

s − ('+ r̲/ s) ÷ t̲ally s
error[type-mismatch]: expected Int, found Float

f̲loat turns the integers into floats first.

Count occurrences: unique and a table

The episode's slide: the equality table of unique votes against votes, summed along each row, gives 3 2 1
From the video: sum each row of the table. Click to enlarge.

Last, count occurrences: how many times each value appears. A loop keeps a map from each value to its count:

let mut counts = HashMap::new();
for v in &votes {
    *counts.entry(v).or_insert(0) += 1;
}

The idiom starts with unique, which gives each value once, in the order they first appear:

u̲nique votes   ⍝ 2 3 1

Equals table compares each value with every vote, so each row marks where one value appears:

(u̲nique votes) '= t̲able votes
┌→──────────┐
↓1 0 1 0 1 0│
│0 1 0 0 0 1│
│0 0 0 1 0 0│
└~──────────┘

Sum along each row, and you have the counts: 2 appears three times, 3 twice and 1 once.

'+ r̲/₂ (u̲nique votes) '= t̲able votes   ⍝ 3 2 1

The trade-off: the table has a cell for every value and every vote. For a long list, that is a lot of cells.

Find positions: where and index of

The episode's slide: where of x greater than 3 turns 0 0 1 0 1 1 into 3 5 6; x index of its maximum is 6
From the video: where, then index of. Click to enlarge.

Now, some more idioms. First, find the positions of the matches. A loop checks each item and keeps the index of each match:

for (i, v) in x.iter().enumerate() {
    if *v > 3 { out.push(i + 1); }
}

The idiom asks the question of every item first, then w̲here turns the ones into positions. Positions count from one:

x > 3           ⍝ 0 0 1 0 1 1
w̲here x > 3     ⍝ 3 5 6

i̲ndexOf finds where a value first appears. Here, it finds the largest:

x i̲ndexOf 'm̲ax r̲/ x   ⍝ 6

Membership: member

The episode's slide: x member of 1 5, drawn 3 1 4 1 5 9 element-of 1 5 equals 0 1 0 1 1 0
From the video: a mask of members. Click to enlarge.

Next, membership: is each item one of a few allowed values? A loop checks each item against the whole set:

for v in &x {
    out.push(allowed.contains(v));
}

m̲ember? asks that of every item at once. The result is a mask of ones and zeros, and a mask can count, choose or find positions:

x m̲ember? 1 5   ⍝ 0 1 0 1 1 0

Moving windows: n-wise

The episode's slide: 3 plus n-wise of 3 1 4 1 5 9 is 8 6 10 15
From the video: plus over every window of three. Click to enlarge.

Next, moving windows: the sum of every three items in a row. A loop slides a window along the list:

for i in 0..x.len() - 2 {
    out.push(x[i] + x[i + 1] + x[i + 2]);
}

n̲wise reduces every window of a given size. Plus, three at a time, adds each group of neighbors, and the result is two items shorter:

3 '+ n̲wise x   ⍝ 8 6 10 15

Sort by a key: grade, then select

The episode's slide: grade of ages 40 25 33 19 is 4 2 3 1; selecting those from ids 101 102 103 104 gives 104 102 103 101
From the video: grade, then select. Click to enlarge.

Last, sort by a key. We have people, and we have their ages, and we want the people in order of age. A loop pairs them, sorts the pairs and keeps the people:

let mut p: Vec<_> = ids.iter().zip(&ages).collect();
p.sort_by_key(|(_, age)| **age);
let out: Vec<_> = p.iter().map(|(id, _)| **id).collect();

g̲rade gives the positions that would sort the ages, and s̲elect takes the people at those positions. The youngest comes first:

ids ← 101 102 103 104
ages ← 40 25 33 19
g̲rade ages                ⍝ 4 2 3 1
(g̲rade ages) s̲elect ids   ⍝ 104 102 103 101

One grade can order many lists the same way.

More than a shorter loop

An array idiom is more than a shorter spelling of a loop. It captures a pattern that keeps coming back. Once you see the pattern, you can reason about the whole operation, reuse it and test it, and often make it faster apart from the program that uses it. The goal is not to remove every loop. The goal is to say the problem at the most useful level.

Coming up, and an exercise

The next episode tours the family of array languages: APL first, then J and K, then BQN, and last X_eTaL, and what each one chose.

Before then, try this in the browser editor. Take 3 1 4 1 5 9. Find its sum and its largest value. Find its running totals. Count the values greater than three. Then find the adjacent differences. (To type it, use the ASCII it is drawn from: := for ←, r_/ for r̲/, s_\ for s̲\, d_rop for d̲rop.)

Closing

I started developing X_eTaL as an alternative to using Python for machine learning. NumPy seems to be heavily influenced by array languages, so I wanted my own approach to array languages. I ended up making the language more general-purpose. I also wanted to show how to extend the language so that the base language stays small. Later in the video series I will show some ways to do this.