Symmetries in Boolean Scan
Recorded: Oct. 16, 2026, 9:23 p.m.
| Original | Summarized |
Symmetries in boolean scans CRC Home Symmetries in boolean scans Andrea Piseri Array languages like APL are famous for using many pretty squiggles for APL programmers have come to rely on these optimizations, for example the Any respectable APL has a tight loop implemented in native code dedicated to Table of Contents Scans and folds Truth tables as finite state machines Appendix B. Efficient implementation of boolean scans Xor Scans and folds fold is a higher order function generalizing the concept of iterating over scan is the same, but instead of returning the final value of the In both cases an initial value may or may not be provided, and in the second APL represents these functions with the operators / and \, so that 10 = +/ 1 2 3 4 In the rest of this article, I’ll be using a fantasy dialect of APL modified to Algorithmic esoterica When I say APLers rely on these, I really mean it! scans, folds, reverse scans, Folding (from the right) with subtraction gives an alternating sum, that’s cute. APL programs go beyond that. What does scanning with the less-than function do? The issue here is that APL needs escape hatches to handle data dependencies in Case study: Resolving quotes Say you have a string of text containing quote characters, and you want to tell bool in_quotes = false; While in APL you would write the following, where the result is an array containing the values of in_quotes тЖР тЙа\string='"' To see why this works, let’s make the C version branchless by encoding the if statement bool in_quotes = false; Boolean scans: how many do we really need? APL has a lot of primitives. it’s the only language I know of which has all non-trivial binary Common name тИз > < тЙа тИи тН▒ = тЙе тЙд тН▓ This is an issue on an implementer’s side, because many primitives mean many Telling which of these are really useful only looking at the truth tables is Is there some way that we can reduce the implementation work without sacrificing Scan composition rules The structure of the scan тН║ f\ тН╡ is as follows: Suppose we want to do some pre-processing with a function g to alter the behaviour of the scan: The motivation for looking at this is that preprocessing a boolean array with a It’s apparent that the right argument to f is being fed through g at each step in the тН║ f\ g┬и тН╡ тЖРтЖТ тН║ (fтИШg)\ тН╡ Equivalent Haskell scanl f x (map g ys) = scanl (\x y -> f x (g y)) x ys If g is any function, where тИШ is APL’s composition operator "jot" that satisfies тН║ fтИШg тН╡ тЖРтЖТ тН║ f (g тН╡) It’s a little trickier to see what effect post-processing with g would have: It may look exactly like before, but notice that the input to each subsequent f call This is a scan diagram using the function {g ((gтНг┬п1) тН║) f тН╡}, except the initial value x has been preprocessed with g. g┬и тН║ f\ тН╡ тЖРтЖТ (g тН║) (gтНд(gтНг┬п1тНЫf))\ тН╡ Equivalent Haskell map g (scanl f x ys) = scanl (\x y -> g (f (ig x) y)) (g x) ys Again some composition operators have been used: (gтНг┬п1) g тН╡ тЖРтЖТ тН╡ тНЭ APL can sometimes find inverses by itself! And finally we can put these two relations together to find a third. g тН║ f\ g тН╡ тЖРтЖТ (g тН║) gтНд(gтНг┬п1тНЫfтИШg)\ тН╡ Equivalent Haskell map g (scanl f x (map g ys)) = scanl (\x y -> g (f (ig x) (g y))) (g x) ys Truth table shuffles In particular, we are interested in seeing which pairs of primitives are We represent all of the truth tables at once as the array a with shape 10 2 2 a Composing on the right argument with ~ is the same as reversing the last axis with pre тЖР тМ╜[2] a Negating the output is just a matter of negating each entry of the table; if we do this, we must also post тЖР ~ тМ╜[1] a And of course we can do both transformations at once both тЖР ~ тМ╜[1] тМ╜[2] a Now we can find out who’s related to whom by searching for the truth tables we got in the original array: index тЖР тЖС(тКВa)тН│┬иa pre post both тФМтЖТтФАтФАтФАтФАтФАтФАтФАтФАтФАтФАтФАтФАтФАтФАтФАтФАтФАтФАтФР Now that we know this, we can index into the list of the symbols the truth tables referred to: 'тИз><тЙатИитН▒=тЙетЙдтН▓'[index] тФМтЖТтФАтФАтФАтФАтФАтФАтФАтФАтФАтФР Now, how do we interpret this? along the top row are the Conclusion We can see that the set тИз, <, тЙа covers all columns at None of this is completely new, by the way. The trick тН║ тЙа\ тН╡ тЖРтЖТ тН║ =\ ~тН╡ Appendix A. Brainstorming and observations I originally discussed this on the APL farm discord server, where some of the users Truth tables as finite state machines In the K language, the form x f\ y, is equivalent to the x a\ y form, where ( x a\ ~y) = x ( |'a)\ y Equivalent Haskell runFsm a x ys = scan (\x y -> (a !! x) !! y) x ys runFsm a x $ map (1 -) ys = runFsm x ( map reverse a) ys Invariants under the given transformations The transformations we gave permute the rows or columns of the tables On these, the transformation ~тМ╜[0]a can be applied so that there are 3 0s, Appendix B. Efficient implementation of boolean scans Xor A xor scan on a machine word can be implemented efficiently in a few instructions by a typical prefix doubling uint64_t xorscan_word (uint64_t word) { We only need to handle the carry from the previous word. The typical way to do this would be void xorscan_bad (bool initial, uint64_t *words, size_t n) { This compiles to the following core loop, which runs at around 3-4 bits per cycle. Assembly output .loop: On a CPU with super-scalar execution, it would be nice if we could delay the usage of the previous result until void xorscan_good (bool initial, uint64_t *words, size_t n) { This is much faster, processing up to 10.5 bits per cycle. Assembly output .loop: If the CPU supports a carry-less multiply instruction (many modern CPUs do!) then xorscan_word can be implemented as carry-less multiplication with the word 0xffffffffffffffff (all ones). And All of the above (except for the carry-less multiply) can be applied verbatim, by replacing ^ with &; however there is a faster Firstly, a single-word and scan can be implemented much more simply than xor uint64_t andscan_word (uint64_t word) { This works because adding one turns the first run of ones into a run of Here is an example, with the bits ordered from least to most significant. word word+1 ~(word + 1) word & ~(word + 1) To extend this to work on an array of words, we observe that at most one word The full implementation might be something like the following. void andscan (bool initial, uint64_t *words, size_t n) { This produces two separate loops, the first and most intensive of them can do 62 bits per cycle, while the Assembly output .loop: Less-than This is the most complicated case, and the solution I’ll present comes from the uint64_t ltscan_word (uint64_t word) { Here is an example, again in little endian bit order. word word << 1 guard parity parity ^ odd result Shifting and setting the odd bits controls whether or not a borrow chain is Like the xor case, the trivial way to chain these together is to clear the void ltscan (bool init, uint64_t *words, size_t n) { This particular version can do 8.8 bits per cycle. Assembly output .loop: 1. Yes, a sufficiently smart(tm) compiler can do this with user-defined code too, but that’s expensive and APL existed at a time where interpreters had to be very simple. 2. When called on a non-empty list 3. "direct function", APL’s name for a lambda; тН║ is the implicitly defined first argument, and тН╡ is the second. 4. For those who know APL already, APL’s scan is only equivalent to what I wrote if the function argument is associative, because traditionally APL has a really idiosyncratic scan operator. I’ll consider an imaginary variant of APL that defines scan to operate left to right and with an explicitly given initial value; dzaima/APL, BQN and K all do have this version of scan, but are otherwise incompatible with the rest of the code in this article. KAP is almost a good fit, but doesn’t support giving an initial value to scan, which introduces ugly edge cases to the equations. 5. I recently found an idiom reported in an old IBM document that used a fold with modulo to check if the last element of a list was one or not. I assume that operation was recognized by the interpreter, but it would have been an incredibly bad idea to call that code idiomatic if it weren’t. 6. There is a linear dependency chain through all of the data, so the absolute maximum a scalar loop could do is one element per cycle 7. suggested by DiscoDoug 8. suggested by Marshall 9. Marshall describes this in his implementation notes for BQN Last updated 2026-08-27 11:19:48 +0200 |
The document explores the relationship between array operations, boolean logic, and efficient algorithmic implementation, focusing on the concepts of scans, folds, and the symmetries inherent in boolean function transformations. Array languages like APL utilize primitives that benefit from interpreter optimizations, which is reflected in how operations like summation are handled natively. The concepts of scan and fold are introduced as higher-order functions, where scan returns a collection of intermediate accumulator values, and fold repeatedly applies a binary function to an accumulator and an element from an ordered collection, generalized by operators like / and \ in APL. The discussion shifts to the algorithmic esoterica of using these operations, noting that APL relies heavily on scans and folds for manipulating data, and that avoiding explicit iteration is crucial for performance when compared to native code execution. The text provides a case study on using boolean scans to determine if elements within a string are inside quote marks, demonstrating how iterative boolean comparisons can be expressed functionally. A core focus is placed on the relationship between various binary boolean functions, defined by their truth tables. The document systematically analyzes the transformations that occur when combining scans and post-processing a boolean array with unary functions. It derives composition rules, demonstrating how applying functions like negation and scanning can be interchanged or modified using compositional operators, leading to complex but mathematically sound equations that relate different primitives. These symmetries are explored by examining how these transformations affect the truth tables of primitives, leading to deductions about the relationships between operations. The analysis also delves into the practical implementation of boolean scans, specifically examining fundamental operations such as XOR, AND, and less-than. The author details how these operations can be implemented efficiently using bitwise manipulations, suggesting methods that exploit properties of addition and negation to perform these scans in a highly optimized manner on machine words. For XOR, a specialized prefix doubling technique is discussed, and for AND and less-than comparisons, methods involving bit shifts and masks are presented. These bitwise techniques demonstrate how complex relational checks can be mapped onto highly efficient, low-level operations on the CPU, sometimes achieving significantly better performance than naive implementations by exploiting associativity and the properties of carries. Finally, the text summarizes that by understanding these inherent symmetries and applying fast implementations, it is possible to derive decent implementations for other necessary operations, reducing implementation time and executable size without sacrificing performance. This involves recognizing that the structure of the APL scan operator must be considered in relation to the functional structure, and that certain shortcuts are already known within the context of functional programming history. The discussion concludes by suggesting that advanced compiler techniques can handle these optimizations, but the mathematical structure of the primitives themselves reveals deeper inherent relationships. |