Loops
for and while statements.
IRL includes statements for making loops in the action part of technical rules.
For loop
The for statement
provides a compact way to iterate over a range of values.
The
general form of the for statement can be expressed
like this:
then{
for (initialization; test; increment) {
statements
}
}The expression initialization is
used to initialize the loop. It is run once at the beginning
of the loop. The test expression determines when
to terminate the loop. This expression is evaluated at the top of
each iteration of the loop. When the expression evaluates to false,
the loop terminates. Finally, increment is an expression
that is invoked after each iteration through the loop. Here is an
example:
then {
int ?i = 1;
int ?j = 1;
for ( ?i = 1; ?i <= 3; ?i++ ) {
for ( ?j = 1; ?j <= 3; ?j++ ) {
System.out.println(" i =" + ?i + " j = " + ?j ) ;
}
}
}Often for loops are used to iterate
over the elements in an array, or the characters in a string. The
following example uses a for statement to iterate
over the elements of an array and print them:
then {
for (?i = 0; ?i < ?arrayOfInts.length; ?i++) {
System.out.println(?arrayOfInts[?i] + " ");
}
}While loop
You
use a while statement to continually run a block
of statements while a condition remains true. The general syntax of
the while statement is:
then {
while (test) {
statements
}
}First the while statement evaluates
the test expression, which must return a boolean
value. If the test returns true,
then the while statement runs the statements
associated with it. The while statement continues
testing the test expression and executing its block
until the test returns false. Here
is an example of a while loop:
then {
int ?i = 0 ;
while ( ?i <= 3 ) {
System.out.println( ?i ) ;
?i++ ;
}
}The following example uses a while statement
in the action part of the rule to iterate over an array of elements
in a variable named elements. The variable elements is
bound to an attribute of a variable c, also named elements.
The variable c is declared in the condition part
of the rule as a collection of ManagedObject().
rule foundManagedObject {
when {
?c: collect ManagedObject();
}
then {
Enumeration ?elements = ?c.elements();
while (?elements.hasMoreElements()) {
System.out.println(elements.nextElement());
}
}
}