foreach

The 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 foreach statement:

rule ConnectivityUpdate{
   when {
      ?n: Node(state == NEW; ?neighbors: neighbors() );
   }
   then {
      foreach ( Node node in ?neighbors ) { 
         node.addLink(?n);
      }
      update (?n);
   }
};

The ConnectivityUpdate rule 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:

  1. The rule condition matches an object Node when the field state equals the static value NEW, and it binds the variable ?neighbors with the vector field neighbors().

  2. If such a Node object is found, the action part can be executed. The foreach statement loops for each neighbor. A new variable node is defined and the method addLink(?n)updates the links of the neighbors to the new nodes.

  3. The last action uses the update command to update the agenda concerning the new node.

Example 2

The second example shows the filtering capability of the foreach statement<

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 string because the instances that are not of the expected type (here String) are filtered out automatically.