Reference > Rule Languages > ILOG Rule Language > IRL Keywords > foreach

Summary

A statement for executing a statement block numerous times. This keyword is used in rule actions or functions.

Syntax

foreach (type variable in expression ) statement;  

Description

The foreach statement is used in the action part of a rule and in a function. It permits you to execute the statement, or a block of statements enclosed in braces ({}), on each element of a collection or an array. It introduces a new variable that may be used for the remainder of the execution block.

The type may be any legal type as in the Java programming language. The expression may be any legal expression that returns a Collection or an Array as in the Java programming language. Any ILOG Rule Language statement may be executed within the statement block as well as arithmetic expressions and method calls.

Example

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

The ConnectivityUpdate rule tests if a new node exists in the network and adds a link to such a new node from each of its neighbors. The single 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(). 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 used in updating the links of the neighbors with the method addLink(?n). The last action uses the update command to update the agenda concerning the new node.

See Also

break, continue, for, in, while