Поделиться через


Authoring rules against a collection

Sometimes you want to write rules against all items in a collection. In WF V1, this is not supported natively but can be achieved in the following manner: (you can come up with other ways too, but the essential idea is you want to simulate looping using forward chaining in rules)

Rule 1 (Highest priority rule; Priority = 2)

IF true

THEN index = 0

Rule 2 (Next higher priority rule; Priority = 1)

IF index > myCollection.Length

THEN Halt

Rule 3 (Lowest priority rule; Priority = 0)

IF myCollection[index].... (do whatever you want with that element)

THEN (whatever action you want); index = index + 1

So, the way rule execution proceeds is that the highest priority rule (Rule 1) executes and initializes the index. The next rule (Rule 2) will fail the condition at the beginning but will be true when you reach the end of the collection, at which time, the ruleset execution will stop due to the special "Halt" action. The lowest priority rule (Rule 3) is really the one you wanted to write to do whatever check / action you wanted to do against an item. The fact that you increment the index causes a re-evaluation of Rule 2 (and hence the ruleset stops when you go through all the elements) and also Rule 3.

Clearly, this is a workable solution, but not really pretty since you have to think about how to get this done when all you really would have liked to do is write the main rule (that is Rule 3). In our next version, this is one of the things we are going to make easier by providing native support for collections. How that will look is still being discussed, so I will not write about how will be able to write it, but imagine accomplishing the above scenario with just Rule 3 and some special syntax to indicate to the WF V.Next rule engine to manage the collection underneath for you.