man bqn/counting

Counting without loops: Group, Classify and Indices in BQN

lib / BQN 9 mindraft

checked against: CBQN 2bf102f

How do you count how often each value occurs in a list, in a language whose answer to “write a loop” is “don’t”?

BQN gives several answers. There is a hash map, •HashMap, for people who want one. There is the all-pairs comparison an array programmer reaches for first. There is Classify followed by Group. And there is /⁼, the inverse of Indices, which the BQN documentation calls “the best way to perform this counting task”. This article runs all four on the same list and reads what CBQN (the C implementation, at commit 2bf102f, 2026-11-22) does inside each one. Timings are from an Apple M2 Pro.

The short version

  • {+´𝕩=x}¨⍷x compares every distinct value with every element: n × k work.
  • ≠¨⊔⊐x numbers the distinct values, groups positions by number and takes the length of each group. CBQN’s Classify uses a lookup table indexed by value when the range is small and a hash table otherwise; Group counts first and then copies every position into its group.
  • /⁼x counts each natural number directly into a table. For a long list of 4-byte integers CBQN counts in 64-element chunks and switches to one-increment-per-run when a chunk holds long runs of equal values.
  • On 100,000 random integers below 100,000, /⁼ took 0.10 ms, ≠¨⊔⊐ 0.93 ms, a •HashMap loop 8.2 ms and the all-pairs version 374 ms.

Four ways on a small list

x ← 3‿1‿3‿0‿3‿1
•Show ⍷ x
•Show ⊐ x
•Show ⊔ ⊐ x
•Show ≠¨ ⊔ ⊐ x
•Show /⁼ x
•Show / 1‿2‿0‿3
•Show {+´𝕩=x}¨ ⍷ x

Reading it glyph by glyph: ← names a value and ‿ joins numbers into a list. ⍷ (Deduplicate) keeps the first copy of each value. ⊐ (Classify) replaces each element with the index of its value in ⍷ x. ⊔ (Group) turns a list of group numbers into the list of positions in each group. ≠¨ takes the length (≠) of each (¨) group. / (Indices) repeats each position as many times as the count there says, and ⁼ (Undo) inverts a function, so /⁼ turns positions back into counts. In the last line the block {…} runs once per distinct value with that value as 𝕩; 𝕩=x is a list of 1s where x equals it, and +´ folds addition over that list.

$ bqn count_demo.bqn
⟨ 3 1 0 ⟩
⟨ 0 1 0 2 0 1 ⟩
⟨ ⟨ 0 2 4 ⟩ ⟨ 1 5 ⟩ ⟨ 3 ⟩ ⟩
⟨ 3 2 1 ⟩
⟨ 1 2 0 3 ⟩
⟨ 0 1 1 3 3 3 ⟩
⟨ 3 2 1 ⟩

The results come in two shapes. ≠¨⊔⊐x and the all-pairs version give one count per distinct value, in first-appearance order, lined up with ⍷ x: 3 appears three times, 1 twice, 0 once. /⁼ x gives one count per number from 0 to the maximum, so the position is the value: one 0, two 1s, no 2s, three 3s. That only works for natural numbers, and the list is as long as the largest value plus one, whether or not the values in between occur.

Classify: a table or a hash

Classify on a list of 4-byte integers (indexOf_c1 in selfsearch.c) starts by finding the minimum and maximum. If the range is under five times the length, it allocates a table covering the range, fills it with a “not seen” marker, and walks the list once:

#define DOTAB(T) /* leaves 1+max in u */ \
  i32 u=0;                                                   \
  for (usz i=0; i<n; i++) {                                  \
    T j=xp[i]; i32 t=tab[j];                                 \
    if (t==n) tab[j]=u++;                                    \
    rp[i]=tab[j];                                            \
  }

A value seen for the first time gets the next class number u, and every element gets its value’s class. Nothing is hashed. With a wider range CBQN tries a Singeli hash table for 4-byte keys, and if that gives up after too many collisions, it falls back to a generic hash map. 1- and 2-byte lists always use a full-size table (256 or 65,536 entries), and lists shorter than 12 compare all pairs.

The table path is easy to see from outside. Multiplying the same values by 1,000 doesn’t change the number of distinct values or the type, only the range:

⊐x           i32arr  0.405 ms
⊐ (×1000)    i32arr 0.964 ms

Deduplicate takes another route. The comment at the top of selfsearch.c says “Except for trivial cases, ⍷ is implemented as ∊⊸/”: Mark Firsts (∊, a 1 at the first copy of each value) and then Replicate (/) to keep those elements. For 4-byte values Mark Firsts goes straight to the hash table, with a radix-based lookup as the fallback, and has no small-range table. On the list timed below, ⍷ took 0.61 ms and ⊐ 0.41 ms; ⍷ also pays for the filter.

Group: count, then copy

Monadic Group on a flat list is defined in CBQN as the dyadic form with the positions as the right argument:

B range = C1(ud, m_f64(IA(x)));
return C2(group, x, range);

That is x ⊔ ↕≠x (↕ is Range, ≠ is length). group_simple then gathers statistics in one pass (maximum, whether the list is sorted, how many ¯1s it has, how often consecutive values change). For an unsorted list with many changes it counts the length of each group with len[wp[i]]++, allocates one result list per group, and copies every position into its group in a second pass.

The first of those passes is /⁼ already. So ≠¨⊔⊐x computes the counts, builds tens of thousands of small lists from them, and then ≠¨ measures each list to get the counts back. It is still linear and fast, but it does the counting work and then some.

/⁼: a counting table

slash_im in slash.c handles /⁼. Its implementation comment starts:

// Indices inverse (/⁼), a lot like Group
// Always gives a squeezed result for integer 𝕩
// Boolean 𝕩: just count 1s

For a 4-byte list it looks for a strictly ascending prefix, finds the maximum, rejects negative values, and allocates a table of maximum + 1 counters. The counting itself is a Singeli function, count_i32_i32. It takes the list 64 elements at a time and compares neighbours with vector instructions to mark where runs of equal values end. If the chunk has fewer than 32 runs it adds each run’s length to the table in one step; otherwise it increments the table once per element. Random data gets the plain loop, data with long runs gets fewer, larger increments.

For long 1- and 2-byte lists the counters are 16 bits wide, with an overflow list for counts above 2¹⁵, and the result is narrowed afterwards. “Squeezed” means the result is stored in the smallest type that fits every count, so a list of counts that stay below 128 comes back as one byte per count:

/⁼x          i8arr   0.103 ms

The four, timed

x ← 1e5 •rand.Range 1e5
T ← •internal.Type
Ms ← {(•Repr (⌊0.5+1e3×1e3×𝕩)÷1e3)∾" ms"}
•Out "x: "∾(T x)∾", "∾(•Repr ≠x)∾" values, "∾(•Repr ≠⍷x)∾" distinct"
•Out "/⁼x          "∾(T /⁼x)∾"   "∾Ms 50 /⁼•_timed x
•Out "⊐x           "∾(T ⊐x)∾"  "∾Ms 50 ⊐•_timed x
•Out "⍷x           "∾(T ⍷x)∾"  "∾Ms 50 ⍷•_timed x
•Out "≠¨⊔⊐x        "∾(T ≠¨⊔⊐x)∾"   "∾Ms 50 ≠¨∘⊔∘⊐•_timed x
m ← ⟨⟩ •HashMap ⟨⟩
•Out "HashMap loop          "∾Ms 1 {𝕩 m.Set 1 + 0 m.Get 𝕩}¨•_timed x
•Out "{+´𝕩=x}¨⍷x   "∾(T {+´𝕩=x}¨⍷x)∾"   "∾Ms 1 {+´𝕩=x}¨∘⍷•_timed x
y ← x × 1000
•Out "⊐ (×1000)    "∾(T y)∾" "∾Ms 50 ⊐•_timed y

1e5 •rand.Range 1e5 is 100,000 random integers from 0 to 99,999. •internal.Type names the storage type. 50 F•_timed x runs F x fifty times and returns the average in seconds; Ms turns that into rounded milliseconds, and ∾ joins the pieces of text that •Out prints. ∘ composes functions, so ≠¨∘⊔∘⊐ is the whole Classify-Group-length pipeline as one function. The hash map line makes an empty map (⟨⟩ is an empty list of keys and of values), then for each element reads its count with a default of 0, adds 1, and stores it.

$ bqn count_bench.bqn
x: i32arr, 100000 values, 63239 distinct
/⁼x          i8arr   0.103 ms
⊐x           i32arr  0.405 ms
⍷x           i32arr  0.608 ms
≠¨⊔⊐x        i8arr   0.926 ms
HashMap loop          8.18 ms
{+´𝕩=x}¨⍷x   i8arr   373.703 ms
⊐ (×1000)    i32arr 0.964 ms

/⁼ is 9 times faster than Classify plus Group and 80 times faster than the hash map loop. The hash map loop runs a BQN block 100,000 times, with two method calls each; each primitive is one call into C. The all-pairs version does 100,000 × 63,239 comparisons, about 6.3 billion, and takes over a third of a second.

Curious facts

  • /⁼ was only defined on sorted lists. / always returns a sorted list, so its strict inverse only accepts one. On 2021-12-12 the specification extended /⁼ to any list of natural numbers, and CBQN added support for unsorted arguments the same day.
  • Counting booleans is a popcount. For a bit list, /⁼ counts the 1s and returns two numbers (just one if there are no 1s).
  • /⁼ refuses negative numbers. /⁼ 1‿¯1 fails with “/⁼𝕩: 𝕩 cannot contain negative numbers”. To count arbitrary integers, subtract the minimum first, or classify them.
  • Group lengths and Indices inverse are the same function. The BQN docs show ≠¨⊔ 2‿3‿1‿2 and /⁼∧ 2‿3‿1‿2 giving the same result; Group’s own first pass computes exactly those counts.
  • The hash map keeps order. The spec defines Keys to return keys “in the order they were set”, like a Python dict and unlike most hash tables.

History

  • 2021-05-14: native ⊔ for lists in CBQN (commit c5506657, dzaima).
  • 2021-05-20: “hashmaps, fast ⊐” (b8fe149d) and “native ⍷vec” (c39b06e0).
  • 2021-11-21: “native /⁼” (b0005765).
  • 2021-12-12: the specification extends /⁼ to unsorted lists (BQN commit abfa39c6), and CBQN’s “support unsorted argument for /⁼” (56d14883) lands the same day.
  • 2023-12-04: •HashMap is specified (BQN commit 82b15a3f).
  • 2023-12-14: “SSE2 & NEON /⁼” (94b1d909).
  • 2024-11-15: “Run-based i32 /⁼” (3b103aad), the run detection described above.

Sources

CBQN at commit 2bf102f:

BQN at commit 5abbab9:

Commits: CBQN c5506657, b8fe149d, c39b06e0, b0005765, 56d14883, 94b1d909, 3b103aad; BQN abfa39c6, 82b15a3f.

ls bqn/