21.4. Fibonacci Example: Recurse Rule

rule Recurse
    salience 10
    when
        f : Fibonacci ( value == -1 )
        not ( Fibonacci ( sequence == 1 ) )
    then
        insert( new Fibonacci( f.sequence - 1 ) );
        System.out.println( "recurse for " + f.sequence );
end
  • The Recurse rule matches each asserted Fibonacci object with a value of -1, creating and asserting a new Fibonacci object with a sequence of one less than the currently matched object.
  • Each time a Fibonacci object is added while the one with a sequence field equal to 1 does not exist, the rule re-matches and fires again.
  • The not conditional element is used to stop the rule's matching once we have all 50 Fibonacci objects in memory.
  • The Recurse rule has a salience value so all 50 Fibonacci objects are asserted before the Bootstrap rule is executed.
  • You can switch to the Audit view to show the original assertion of the Fibonacci object with a sequence field of 50, done with Java code. From there on, the Audit view shows the continual recursion of the rule, where each asserted Fibonacci object causes the Recurse rule to become activated and to fire again.