Loops

From ABL
Jump to: navigation, search

Currently, there are no native looping constructs in ABL; however, we can simulate loops with other ABL constructs. Consider the following agent:

package examples;

behaving_entity Loop
{
    int y;

    sequential behavior Caller() {
        // the success test is the exit condition of the loop
        with (success_test{ (y>10) }) subgoal LoopWrapper();
        mental_act { System.out.println("Done with loop!"); }
    }

    // The wrapper is needed so that we can wrap a 'persistent' around
    // the loop body.
    sequential behavior LoopWrapper() {
        // the 'persistent' enables the looping
        with (persistent) subgoal LoopBody();
    }

    // The 'atomic' is redundant in this case because LoopBody has
    // only a mental act, which are performed atomically anyway.  In
    // general, the 'atomic' is needed because the success_test above
    // is a continuously monitored condition and thus might succeed in
    // the middle of the loop body.
    atomic sequential behavior LoopBody() {
        mental_act { 
            System.out.println("y="+y); 
            y++;
        }
    }

    initial_tree {
        with (priority_modifier 1) mental_act { y=1; }
        subgoal Caller();
    }
}

This agent prints the numbers 1 to 10 and a final message. The basic approach to set up a loop is to:

  • write an exit condition for the loop in a success_test,
  • write a wrapper for the loop body that invokes the loop body with a persistent annotation, and
  • write a loop body that is atomic.


Here's a sample run:

% ablc examples/Loop.abl
Reading from file examples/Loop.abl . . .
examples/Loop.abl parsed successfully.
Generating code . . .
ABL compiler took: 0.478 seconds
% javac -cp $ABLPATH:. examples/Loop*.java
% abl examples.Loop
y=1
y=2
y=3
y=4
y=5
y=6
y=7
y=8
y=9
y=10
Done with loop!