-
Hi, Is there a way to iterate over every element of a table without knowing the number of dimensions at function definition time? And generally, how would one write code that's dimension agnostic (if possible)? (sorry if this is covered somewhere, I couldn't find it) Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Great question. In some senses the answer is yes, in others it's no. Specifically, there's no way in the current type system to write a function that can take an arbitrarily-nested index set, like:
However, there are three senses in which the answer is yes: 1. Nested index sets are isomorphic to products of index sets.All
As long as we can express your table indices as a single index set (here How does this help us deal with nested tables? Concretely, nested tables of arbitrary shape
2. Tables themselves can be used as index setsAs of #876, tables themselves can be used as index sets, letting us build index sets whose dimension is determined at runtime, but still tracked by the compiler. For instance, the type Constructing and summing over such an arbitrarily-dimensioned table could be done like so:
From the point of view of This trick is used in the FFT demo to build vectors whose lengths are powers of 2 by definition, having type 3. Record types might someday support iterating over fields.As discussed in #258 and #308, it'd be useful in many contexts to support iteration over the fields of a record type. I think this would allow a stronger |
Beta Was this translation helpful? Give feedback.
Great question. In some senses the answer is yes, in others it's no. Specifically, there's no way in the current type system to write a function that can take an arbitrarily-nested index set, like:
def reduce_over_arbitrary_dims (xs: m=>n=>o...=>y=>z=>Float) : Float = ...
However, there are three senses in which the answer is yes:
1. Nested index sets are isomorphic to products of index sets.
All
for
loops in Dex can already reduce over any index set that you can create, and index sets can be of arbitrary size and shape internally. For instance, here's the type offsum
:def fsum {n} (xs:n=>Float) : Float = ...
As long as we can express your table indices as a single index set (here
n
), al…