are for loops possible in drools?

mh377 picture mh377 · Jul 31, 2010 · Viewed 15.3k times · Source

does anybody know if there is a way to do for loops in drools ?.

I am trying to loop through a list of string to see if one of the strings matches a pattern e.g.

def listOfStrings = ['a','a.b','a.b.c']

for(String s:listOfStrings){
 if(s matches "^a.b.*$"){
 return true 
 }
}

I have written the following rule based on what documentation I could find, but I dont think the syntax is correct

rule "Matcher"
   when
      TestClass : TestClass(($s matches "^a.b.*$") from listOfStrings, count($s))
   then
      TestClass.setResponse( "Condition is True !!" );
end

I am finding it hard to find good documentation on the drl language

I would appreciate any help that anybody can give me


Based on the previous answer, I have tried the following

rule "Matcher"
  when
 TestClass:TestClass(String( this matches "^a.b.*$" ) from listOfStrings)
then
       TestClass.setResponse( "Condition is True !!" );
end 

However, I now get the following error message:

[43,197]: unknown:43:197 Unexpected token 'this'

Answer

Steven Herod picture Steven Herod · Nov 2, 2010

I think you've misunderstood the fundamentals of a rules engine; you need to think a bit differently.

Instead of 'iterating' over the list, you need to break the list into its component strings and insert them individually as facts into working memory.

Only the strings/facts which match the 'when' condition will fire the rule.

You might also want to look into globals and queries. global will allow you to inject a service into your working memory for your consequences to call, and the query might be a way by which you can obtain the matched strings out of working memory.