A Partial Plan-based Solution

Partial plans are an alternative to plan rules. The do a similar thing to goal rules, with the exception that no event is generated, and no rule matching takes place. Basically, partial plans provide a mechanism to write something analogous to a private method in an Object-Oriented language. They cannot be invoked directly, nor do they have a context. Instead, they are invoked from within another plan and ultimately, a plan rule.

  package examples.fibonnacci;
  
  agent PlanFib {
      module System system;
      module Console console;

      rule +!main(list args) {
          long S = system.currentTimeMillis();
          fib(long X, 1l, 1l, 500l);
          console.println("FIB(50) = " + X);
          console.println("Duration: " +
              (system.currentTimeMillis() - S));
          system.exit();
      }
  
      plan fib(long R, long A, long B, long N) {
          if (N == 3) {
              R = A + B;
          } else {
              fib(R, B, A+B, N-1);
          }
      }
  }

This program has similar performance to the better recursive solution. However in a scenario where a lot of events are being generated, this should work more quickly.