Resolution of Axis Reduction in Mixed-Rank Nested Arrays
In APL, the reduction operator (+/) resolves the axis of reduction by treating a nested array as a 1D sequence of elements, regardless of the internal rank of those elements. The reduction is applied to the outermost axis. If the nested array contains elements of mixed ranks (e.g., some scalars and some vectors), APL does not implicitly flatten the internal structures; it attempts to apply the binary operator to the elements as they are encountered in the sequence.
Rank Error vs. Implicit Flattening
APL does not implicitly flatten nested structures during a reduction. The distinction between a successful operation and a rank error depends on the compatibility of the binary operator with the ranks of the elements being reduced:
- Rank Error: Occurs when the binary operator (e.g.,
+) encounters two elements whose ranks are incompatible according to APL's rank rules. For example, attempting to add a 2D matrix to a 1D vector where the dimensions do not align for broadcasting will trigger a rank error.
- Successful Reduction: Occurs if the operator can handle the mixed ranks via broadcasting or if the elements are of a type that the operator accepts (e.g., adding a scalar to a vector).
Steps to Resolve Rank Mismatches in Tacit Functions
To ensure a consistent output shape when operating across a specific axis of a nested array without manual raveling, use the following strategies:
- Normalize Rank: Use the
⎕rank or ⊃ (enclose) operator to ensure all elements in the nested array are promoted to a uniform rank before the reduction.
- Explicit Axis Specification: When using functions that support axis arguments, explicitly define the axis to avoid the default behavior of reducing the leftmost axis.
- Conditional Flattening: If the goal is to treat the structure as a flat sequence, use the
(⍴⍴X) or (⍳⍴X) logic to determine if a ⊃ (flatten/unwrap) is required before the reduction operator is applied.
Diagnostic Requirement
To provide a more precise tacit implementation, please specify: Are the nested elements of varying ranks intended to be treated as scalars (via a sum of sums) or as aligned tensors?