Using APL’s Each Operator (¨) to Avoid Explicit Loops
Learn how APL’s each operator (¨) lets you apply a function to every array element without writing explicit loops, with a concrete matrix‑scaling example and notes on nesting and performance.
01 Nov 2025, 12:36 UTC

Problem: Repetitive Scalar Operations in APL
When you need to apply the same calculation to every element of an array, writing an explicit loop or recursion adds noise and obscures the intent of the code.
How the Each Operator (¨) Works
The each operator takes a function on its left and an array on its right. It invokes the function once for every element of the right‑hand array, collecting the results into a new array that has exactly the same shape as the input. If the function returns a scalar, the result stays flat; if it returns an array, the result becomes nested, increasing the depth by one.
Worked Example: Scaling a Matrix
Start an APL session (e.g., dyalog or gnuapl) and enter the following line:
⎕← {⍵×2} ¨ 2 3⍴⍳6
This creates a 2×3 matrix containing the numbers 1 through 6, then uses each to multiply every element by two. The interpreter returns a new 2×3 matrix whose values are the doubled numbers. You can verify the shape with ⍴ {⍵×2} ¨ 2 3⍴⍳6 which should show 2 3.
Trade‑off: Nesting and Memory
When the function supplied to each returns an array, the result is a nested array. For large data sets this can cause a temporary spike in memory because each element’s result is kept separate until the whole expression finishes. If you only need a flattened outcome, apply ↑ (mix) or ↓ (split) after each, or consider the rank operator (⍥) when the function already handles higher ranks.
Actionable Closing
Use each when you have a rank‑polymorphic function (one that works on scalars) and you want to keep the original array shape. If the function expects a specific rank, reshape the data first or wrap it in a rank‑polymorphic helper. For cases where each would create deep nesting, flatten the result with mix or switch to the rank operator to avoid extra memory usage.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.