foreach - create an appropriately-sized Array or List by evaluating expr according to the arr-expr template
foreach (arr-expr) { expr }
arr-expr must be an array index expression. The indexes of arr-expr must be simple names.
The arr-expr is an array index expression. The indexes of this expression must be simple names. Both regular indexes and flat indexes are allowed. The expr may be any expression, and it may optionally use the names declared in the indexes of arr-expr.
The arr-expr dictates the shape of the resulting array. If a regular N-dimensional index is used, the shape of the resulting array is the first N elements of the shape of the source array. If a flat index is used, then the shape of the resulting array is the same as the shape of the source array.
The expr may refer to the base of arr-expr by using the ?* pseudo-constant. This is especially useful if the base was produced by an expression.
Note that foreach always creates a heterogeneous List or Array. Note also that foreach is an expression; contrast it with forall which is a statement.
a = [2,3].iterate() // A single index creates a 1-D result b = foreach (a[i]) { "Row " ## (i => String) } b +-----+ +-----+ |Row 0| |Row 1| +-----+ +-----+ // Two indexes creates a 2-D result b = foreach (a[i,j]) { {i,j} } b +---+ +---+ +---+ |0 0| |0 1| |0 2| +---+ +---+ +---+ +---+ +---+ +---+ |1 0| |1 1| |1 2| +---+ +---+ +---+ // A flat index creates a result of the same shape as the source array b = foreach (a#[i]) { Char('a'+i) } b a b c d e f // Use the ?* constant to refer to the base array b = foreach ((a*10)[i,j]) { ?*[i,j] } b 0 10 20 30 40 50 // Attempting to access more elements than present in the array // throws a ShapeCheck error b = foreach(a[i,j,k]) { 1 } Inconsistent array shape