for

for .. in .. , keyword

The for X in T.X offers a simple iteration mechanism over the values of a specified vector. Unlike each blocks, there is no diagram, no observation table, etc.

All iteration constructs in Envision have a bounded number of iterations; while loops are not supported.

This mechanism allows to cross a table with itself, as illustrated by:

table T = extend.range(5)

T.S = for N in T.N
  return N * sum(T.N) when (N < T.N)

show table "" with T.N, T.S

Several tables can be used as long as the common table exists and is unique:

table T = extend.range(5)
table U[u] = by T.N mod 2

T.S = for tn in T.N, un in u
  return un + tn * sum(T.N) when (tn < T.N)

show table "" with T.N, T.S

Iteration order with scan

The scan option defines the iteration order. It is required when using keep and forbidden otherwise. The scan expression must depend only on data available before the loop starts. Expressions computed inside the loop are rejected to avoid rebuilding indices per iteration.

table T = extend.range(3)
acc = 0

T.Cum = for n in T.N scan T.N
  keep acc
  acc = acc + n
  return acc

Filtering with when

when filters iterations and can only be used on loops without return.

table T = extend.range(5)
s = 0

for n in T.N scan T.N when n mod 2 == 1
  keep s
  s = s + n

show scalar "odd sum" with s

Cross-table return

Returning vectors from other tables requires a matching cross table:

table T = extend.range(3)
table U = extend.range(2)
table TU = cross(T, U)

T.A, TU.B = for n in T.N
  a = n
  U.B = n * U.N
  return (a, U.B)

Range iteration

for n = low..high iterates over integer ranges. scan is not allowed and return is forbidden.

a = 0
for n = 1..3
  keep a
  a = a + n
show scalar "a" with a

Allowed statements

The for body allows assignments, keep, return, when, and nested loops. Statements like read, write, show, def, and where are not allowed.

User Contributed Notes
0 notes + add a note