Page 1 of 1

Iteration on aggregate. REPEAT. WHILE.

Posted: Tue Mar 14, 2023 10:29 am
by azo
Sometimes we need to alter aggregate content during iteration on it.
New element can be added to a aggregate.

The following example demonstrates possible problem.
Initial aggregate size is 3. There are 3 elements in there.
In REPEAT cycle we append one more element
But anyway REPEAT makes only 3 iterations.

Code: Select all

QUERY_FUNCTION aggregate_test : INTEGER;
   LOCAL
      aggr : LIST OF INTEGER;
      res : INTEGER;
   END_LOCAL;
   aggr := [1, 2, 3];
   res := 0;
   REPEAT i := 1 TO xpfSizeOf(aggr);
      IF i = 2 THEN
         aggr ++ 4;
      END_IF;
      res += 1;
   END_REPEAT;
   
   RETURN (res);
END_QUERY_FUNCTION;
ISO 10303 standard says that this is correct behavior.

The numeric_expressions representing the bounds and the increment are evaluated once
on entry to the repeat statement.


Therefore it is recommended to use WHILE control.
In this case xpfSizeOf(aggr) is evaluated at each iteration.

Code: Select all

   i := 1;
   REPEAT WHILE i <= xpfSizeOf(aggr);
      ...
      i := i + 1;
      -- It is possible to insert or delete elements here.
      ...
   END_REPEAT;