The Iterative Version

Last, but not least, we introduce a standard iterative solution. This example, would normally be one of the first discussed for a procedural language, but here, we have left it to last. This is because this approach only works due to the introduction of local variables and assignment in ASTRA.

  package examples.fibonnacci;
      
  agent ItFib {
      module System system;
      module Console console;
      
      rule +!main(list args) {
          long S = system.currentTimeMillis();
          !fib(long X, 500l);
          console.println("FIB(50) = " + X);
          console.println("Duration: " + 
              (system.currentTimeMillis() - S));
          system.terminate();
      }

      rule +!fib(long R, long N) {
          long A = 1l;
          long B = 1l;
  
          int i = 3;
          while (i <= N) {
              R = A + B;
              A = B;
              B = R;
              i = i + 1;
          }
      }
  }

This solution needs little explanation, and is slightly faster than the better recursive and plan-based solutions (~ 5% faster).