onsdag, februari 28, 2007

Recursion in Rules

Long time since I wrote something about Rules, so, here is a small sample for using recursion in Rules. Implementing recursion in Rules is fairly easy, just assert a new fact in the action-block of a rule, that's it. By asserting a new fact to the system, the system will re-evaluate, and recursion has taken place.

Below is an example that will illustrate this, it will find and print all ancestor relationships that are the result of three parent relationships. Andy is a parent of Betty, Betty is a parent of Charlie and Charlie is a parent of Donna. Which are the resulting ancestor relationships?

Running this program will reveal the result...

ruleset main {

class Parent {
String a;
String b;
}

class Ancestor {
String a;
String b;
}

// Convert a Parent relationship to an Ancestor relationship
rule parentToAncestor {
if ( (fact Parent p) ) {
assert(new Ancestor(a: p.a, b: p.b));
}
}

// If A is parent of B and B is an Ancestor of C, then A is an Ancestor of C
rule parentAndAncestorToAncestor {
if (
(fact Parent p) &&
(fact Ancestor a) &&
p.b.equals(a.a)
) {
assert(new Ancestor(a: p.a , b: a.b));
}
}

// Printout all Ancestors relationships
rule printAncestors {
if (fact Ancestor a) {
println(a.a + " is an ancestor of " + a.b);
}
}

// Setup some parent relations...
{
assert(new Parent(a: "Andy" , b: "Betty"));
assert(new Parent(a: "Betty" , b: "Charlie"));
assert(new Parent(a: "Charlie", b: "Donna"));
}

// Evaluate the ruleset
run();
}


below is the result:

Andy is an ancestor of Donna
Betty is an ancestor of Donna
Charlie is an ancestor of Donna
Andy is an ancestor of Charlie
Betty is an ancestor of Charlie
Andy is an ancestor of Betty

Inga kommentarer:

Skicka en kommentar