foreach
foreach keyword executes a statement
block several times.
Purpose
The foreach statement
is used in the action part of a rule for executing a statement block
numerous times.
Context
Functions or rule actions
Syntax
foreach (type variable in expression ) statement;
Description
Use the foreach statement
in the action part of rule and in functions to execute the statement,
or a block of statements enclosed in braces ({}),
on each element of a collection or array. The foreach statement
introduces a new variable which you can use in the remainder of the
execution block.
The variable type can be any valid type, as
in the Java™ programming language.
The expression can be any legal expression that returns a Collection or Array value
type, as in the Java programming
language. The statement block can execute any IRL statement and any
arithmetic expressions and method calls.
This foreach statement slightly differs from the corresponding statement in Java in that it automatically filters out the objects that are not
of the expected type. See the second example below.
Example
Here
are two examples of foreach statements.
- Example 1
The first example shows the basic behavior of the
foreachstatement:rule ConnectivityUpdate{ when { ?n: Node(state == NEW; ?neighbors: neighbors() ); } then { foreach ( Node node in ?neighbors ) { node.addLink(?n); } update (?n); } };The
ConnectivityUpdaterule tests whether a new node exists in the network and adds a link to it from each of its neighbors. This rule is processed as follows:The rule condition matches an object
Nodewhen the fieldstateequals the static valueNEW,and it binds the variable?neighborswith the vector fieldneighbors().If such a
Nodeobject is found, the action part can be executed. Theforeachstatement loops for each neighbor. A new variablenodeis defined and the methodaddLink(?n)updates the links of the neighbors to the new nodes.The last action uses the
updatecommand to update the agenda concerning the new node.
- Example 2
The second example shows the filtering capability of the
foreachstatement<List l = new ArrayList(); l.add(1); l.add(null); l.add("a string"); foreach ( String s in l) { System.out.println(s); }This statement block produces
a stringbecause the instances that are not of the expected type (hereString) are filtered out automatically.